Search Results

Search found 1591 results on 64 pages for 'oop criticism'.

Page 26/64 | < Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >

  • Extend DOMElement object

    - by Comma
    How could I exdend objects provided with Document Object Model? Seems that there is no way according to this [issue][2]. class Application_Model_XmlSchema extends DOMElement { const ELEMENT_NAME = 'schema'; /** * @var DOMElement */ private $_schema; /** * @param DOMDocument $document * @return void */ public function __construct(DOMDocument $document) { $this->setSchema($document->getElementsByTagName(self::ELEMENT_NAME)->item(0)); } /** * @param DOMElement $schema * @return void */ public function setSchema(DOMElement $schema){ $this->_schema = $schema; } /** * @return DOMElement */ public function getSchema(){ return $this->_schema; } /** * @param string $name * @param array $arguments * @return mixed */ public function __call($name, $arguments) { if (method_exists($this->_schema, $name)) { return call_user_func_array( array($this->_schema, $name), $arguments ); } } } $version = $this->getRequest()->getParam('version', null); $encoding = $this->getRequest()->getParam('encoding', null); $source = 'http://www.w3.org/2001/XMLSchema.xsd'; $document = new DOMDocument($version, $encoding); $document->load($source); $xmlSchema = new Application_Model_XmlSchema($document); $xmlSchema->getAttribute('version'); I got an error: Warning: DOMElement::getAttribute(): Couldn't fetch Application_Model_XmlSchema in C:\Nevermind.php on line newvermind

    Read the article

  • How to set default values to all wrong or null parameters of method?

    - by Roman
    At the moment I have this code (and I don't like it): private RenderedImage private RenderedImage getChartImage (GanttChartModel model, String title, Integer width, Integer height, String xAxisLabel, String yAxisLabel, Boolean showLegend) { if (title == null) { title = ""; } if (xAxisLabel == null) { xAxisLabel = ""; } if (yAxisLabel == null) { yAxisLabel = ""; } if (showLegend == null) { showLegend = true; } if (width == null) { width = DEFAULT_WIDTH; } if (height == null) { height = DEFAULT_HEIGHT; } ... } How can I improve it? I have some thoughts about introducing an object which will contain all these parameters as fields and then, maybe, it'll be possible to apply builder pattern. But still don't have clear vision how to implement that and I'm not sure that it's worth to be done. Any other ideas?

    Read the article

  • Perl - Calling subclass constructor from superclass (OO)

    - by Emmel
    This may turn out to be an embarrassingly stupid question, but better than potentially creating embarrassingly stupid code. :-) This is an OO design question, really. Let's say I have an object class 'Foos' that represents a set of dynamic configuration elements, which are obtained by querying a command on disk, 'mycrazyfoos -getconfig'. Let's say that there are two categories of behavior that I want 'Foos' objects to have: Existing ones: one is, query ones that exist in the command output I just mentioned (/usr/bin/mycrazyfoos -getconfig`. Make modifications to existing ones via shelling out commands. Create new ones that don't exist; new 'crazyfoos', using a complex set of /usr/bin/mycrazyfoos commands and parameters. Here I'm not really just querying, but actually running a bunch of system() commands. Affecting changes. Here's my class structure: Foos.pm package Foos, which has a new($hashref-{name = 'myfooname',) constructor that takes a 'crazyfoo NAME' and then queries the existence of that NAME to see if it already exists (by shelling out and running the mycrazyfoos command above). If that crazyfoo already exists, return a Foos::Existing object. Any changes to this object requires shelling out, running commands and getting confirmation that everything ran okay. If this is the way to go, then the new() constructor needs to have a test to see which subclass constructor to use (if that even makes sense in this context). Here are the subclasses: Foos/Existing.pm As mentioned above, this is for when a Foos object already exists. Foos/Pending.pm This is an object that will be created if, in the above, the 'crazyfoo NAME' doesn't actually exist. In this case, the new() constructor above will be checked for additional parameters, and it will go ahead and, when called using -create() shell out using system() and create a new object... possibly returning an 'Existing' one... OR As I type this out, I am realizing it is perhaps it's better to have a single: (an alternative arrangement) Foos class, that has a -new() that takes just a name -create() that takes additional creation parameters -delete(), -change() and other params that affect ones that exist; that will have to just be checked dynamically. So here we are, two main directions to go with this. I'm curious which would be the more intelligent way to go.

    Read the article

  • PHP Session Class and $_SESSION Array

    - by Gianluca Bargelli
    Hello, i've implemented this custom PHP Session Class for storing sessions into a MySQL database: class Session { private $_session; public $maxTime; private $database; public function __construct(mysqli $database) { $this->database=$database; $this->maxTime['access'] = time(); $this->maxTime['gc'] = get_cfg_var('session.gc_maxlifetime'); session_set_save_handler(array($this,'_open'), array($this,'_close'), array($this,'_read'), array($this,'_write'), array($this,'_destroy'), array($this,'_clean') ); register_shutdown_function('session_write_close'); session_start();//SESSION START } public function _open() { return true; } public function _close() { $this->_clean($this->maxTime['gc']); } public function _read($id) { $getData= $this->database->prepare("SELECT data FROM Sessions AS Session WHERE Session.id = ?"); $getData->bind_param('s',$id); $getData->execute(); $allData= $getData->fetch(); $totalData = count($allData); $hasData=(bool) $totalData >=1; return $hasData ? $allData['data'] : ''; } public function _write($id, $data) { $getData = $this->database->prepare("REPLACE INTO Sessions VALUES (?, ?, ?)"); $getData->bind_param('sss', $id, $this->maxTime['access'], $data); return $getData->execute(); } public function _destroy($id) { $getData=$this->database->prepare("DELETE FROM Sessions WHERE id = ?"); $getData->bind_param('S', $id); return $getData->execute(); } public function _clean($max) { $old=($this->maxTime['access'] - $max); $getData = $this->database->prepare("DELETE FROM Sessions WHERE access < ?"); $getData->bind_param('s', $old); return $getData->execute(); } } It works well but i don't really know how to properly access the $_SESSION array: For example: $db=new DBClass();//This is a custom database class $session=new Session($db->getConnection()); if (isset($_SESSION['user'])) { echo($_SESSION['user']);//THIS IS NEVER EXECUTED! } else { $_SESSION['user']="test"; Echo("Session created!"); } At every page refresh it seems that $_SESSION['user'] is somehow "resetted", what methods can i apply to prevent such behaviour?

    Read the article

  • How can I handle multiple views of a data object? Which design pattern is acceptable?

    - by tranquil.byte
    I have a person object. class Person { private $name; ... } I need to be able to change how they are displayed on the front-end ( visitors have control ). They can choose list view, grid view, photo view for example. class PersonDisplay { public function displayList() { // Query database // Output html to display in list mode } public function displayPhoto() { // Query database // Output html to display in photo mode } } Is this an acceptable way to handle the presentation of the items on the front-end or is there a specific design pattern I should be researching to help me with this task? Does anyone have any suggestions or ideas where this could go wrong or if this could potentially make maintenance a nightmare? The Person object was just an example very similiar to what I am using.

    Read the article

  • Constructor within a constructor

    - by Chiramisu
    Is this a bad idea? Does calling a generic private constructor within a public constructor create multiple instances, or is this a valid way of initializing class variables? Private Class MyClass Dim _msg As String Sub New(ByVal name As String) Me.New() 'Do stuff End Sub Sub New(ByVal name As String, ByVal age As Integer) Me.New() 'Do stuff End Sub Private Sub New() 'Initializer constructor Me._msg = "Hello StackOverflow" 'Initialize other variables End Sub End Class

    Read the article

  • PHP object class variable

    - by mck89
    I have built a class in PHP and I must declare a class variable as an object. Everytime I want to declare an empty object I use: $var=new stdClass; But if I use it to declare a class variable as class foo { var $bar=new stdClass; } a parse error occurs. Is there a way to do this or must I declare the class variable as an object in the constructor function? PS: I'm using PHP 4.

    Read the article

  • How can I add a field with an array value to my Perl object?

    - by superstar
    What's the difference between these two constructors in perl? 1) sub new { my $class = shift; my $self = {}; $self->{firstName} = undef; $self->{lastName} = undef; $self->{PEERS} = []; bless ($self, $class); return $self; } 2) sub new { my $class = shift; my $self = { _firstName => shift, _lastName => shift, _ssn => shift, }; bless $self, $class; return $self; } I am using the second one so far, but I need to implement the PEERS array in the second one? How do I do it with the second constructor and how can we use get and set methods on those array variables?

    Read the article

  • Is this class + constructor definition pattern overly redundant?

    - by Protector one
    I often come across a pattern similar to this: class Person { public string firstName, lastName; public Person(string firstName, string lastName) { this.firstName = firstName; this.lastName = lastName; } } This feels overly redundant (I imagine typing "firstName" once, instead of thrice could be enough…), but I can't think of a proper alternative. Any ideas? Maybe I just don't know about a certain design pattern I should be using here? Edit - I think I need to elaborate a little. I'm not asking how to make the example code "better", but rather, "shorter". In its current state, all member names appear 3 times (declaration, initialization, constructor arguments), and it feels rather redundant. So I'm wondering if there is a pattern (or semantic sugar) to get (roughly) the same behavior, but with less bloat. I apologize for being unclear initially.

    Read the article

  • Static vs Non Static constructors

    - by Neil N
    I can't think of any reasons why one is better than the other. Compare these two implementations: public class MyClass { public myClass(string fileName) { // some code... } } as opposed to: public class MyClass { private myClass(){} public static Create(string fileName) { // some code... } } There are some places in the .Net framework that use the static method to create instances. At first I was thinking, it registers it's instances to keep track of them, but regular constructors could do the same thing through the use of private static variables. What is the reasoning behind this style?

    Read the article

  • How to fetch populated associated models in CakePHP when calling read()

    - by Code Commander
    I have the following Models: class Site extends AppModel { public $name = "Site"; public $useTable = "site"; public $primaryKey = "id"; public $displayField = 'name'; public $hasMany = array('Item' => array('foreignKey' => 'siteId')); public function canView($userId, $isAdmin = false) { if($isAdmin) { return true; } return array_key_exists($this->id, $allowedSites); } } and class Item extends AppModel { public $name = "Item"; public $useTable = "item"; public $primaryKey = "id"; public $displayField = 'name'; public $belongsTo = array('Site' => array('foreignKey' => 'siteId')); public function canView($userId, $isAdmin = false) { // My problem appears to be the next line: return $this->Site->canView($userId, $isAdmin); } } In my controller I am doing something like this: $result = $this->Item->read(null, $this->request->id); // Verify permissions if(!$this->Item->canView($this->Session->read('userId'), $this->Session->read('isAdmin'))) { $this->httpCodes(403); die('Permission denied.'); } I notice that in Item->canView() $this->data['Site'] is populated with the column data from the site table. But it merely an array and not an object. On the other hand $this->Site is a Site object, but it has not been populated with the column data from the site table like $this->data. What is the proper way to have CakePHP get the associated model as the object and containing the data? Or am I going about this all wrong? Thanks!

    Read the article

  • Constructor Overloading

    - by Mark Baker
    Normally when I want to create a class constructor that accepts different types of parameters, I'll use a kludgy overloading principle of not defining any args in the constructor definition: e.g. for an ECEF coordinate class constructor, I want it to accept either $x, $y and $z arguments, or to accept a single array argument containg x, y and z values, or to accept a single LatLong object I'd create a constructor looking something like: function __construct() { // Identify if any arguments have been passed to the constructor if (func_num_args() > 0) { $args = func_get_args(); // Identify the overload constructor required, based on the datatype of the first argument $argType = gettype($args[0]); switch($argType) { case 'array' : // Array of Cartesian co-ordinate values $overloadConstructor = 'setCoordinatesFromArray'; break; case 'object' : // A LatLong object that needs converting to Cartesian co-ordinate values $overloadConstructor = 'setCoordinatesFromLatLong'; break; default : // Individual Cartesian co-ordinate values $overloadConstructor = 'setCoordinatesFromXYZ'; break; } // Call the appropriate overload constructor call_user_func_array(array($this,$overloadConstructor),$args); } } // function __construct() I'm looking at an alternative: to provide a straight constructor with $x, $y and $z as defined arguments, and to provide static methods of createECEFfromArray() and createECEFfromLatLong() that handle all the necessary extraction of x, y and z; then create a new ECEF object using the standard constructor, and return that Which option is cleaner from an OO purists perspective?

    Read the article

  • Using pointers to adjust global objects in objective-c

    - by Rob
    Ok, so I am working with two sets of data that are extremely similar, and at the same time, these data sets are both global NSMutableArrays within the object. data_set_one = [[NSMutableArray alloc] init]; data_set_two = [[NSMutableArray alloc] init]; Two new NSMutableArrays are loaded, which need to be added to the old, existing data. These Arrays are also global. xml_dataset_one = [[NSMutableArray alloc] init]; xml_dataset_two = [[NSMutableArray alloc] init]; To reduce code duplication (and because these data sets are so similar) I wrote a void method within the class to handle the data combination process for both Arrays: -(void)constructData:(NSMutableArray *)data fromDownloadArray:(NSMutableArray *)down withMatchSelector:(NSString *)sel_str Now, I have a decent understanding of object oriented programming, so I was thinking that if I were to invoke the method with the global Arrays in the data like so... [self constructData:data_set_one fromDownloadArray:xml_dataset_one withMatchSelector:@"id"]; Then the global NSMutableArrays (data_set_one) would reflect the changes that happen to "array" within the method. Sadly, this is not the case, data_set_one doesn't reflect the changes (ex: new objects within the Array) outside of the method. Here is a code snippet of the problem // data_set_one is empty // xml_dataset_one has a few objects [constructData:(NSMutableArray *)data_set_one fromDownloadArray:(NSMutableArray *)xml_dataset_one withMatchSelector:(NSString *)@"id"]; // data_set_one should now be xml_dataset_one, but when echoed to screen, it appears to remain empty And here is the gist of the code for the method, any help is appreciated. -(void)constructData:(NSMutableArray *)data fromDownloadArray:(NSMutableArray *)down withMatchSelector:(NSString *)sel_str { if ([data count] == 0) { data = down; // set data equal to downloaded data } else if ([down count] == 0) { // download yields no results, do nothing } else { // combine the two arrays here } } This project is not ARC enabled. Thanks for the help guys! Rob

    Read the article

  • MustOverride Shared Methods in .Net

    - by Ben
    Hi I have a few class's that inherit from a base class. I want to enforce that all of these Class's implement a shared method foo(). I am not able to create the following on the base class Public MustOvveride Shared Sub foo() as this is not allowed. I also cant create an Interface that defines a Shared Sub Foo() and implement that in my derrived class's, as this also is not allowed. Does anyone know how i should implement this? p.s i realise my example is in VB and i have also tagged C#, the same problem applies to both languages and presumably the same fix would apply.

    Read the article

  • Java - how to tell class of an object?

    - by lkm
    Given a method that accepts as a parameter a certain supertype. Is there any way, within that method, to determine the actual class of the object that was passed to it? I.e. if a subtype of the allowable parameter was actually passed, is there a way to find out which type it is? If this isn't possible can someone explain why not (from a language design perspective)? Thanks Update: just to make sure I was clear void doSomething(MyType myType) { //determine if myType is MyType OR one of its subclasses } Since the method signature specifies the parameter as being MyType, then how can one tell if the object is actually a subtype of MyType (and which one).

    Read the article

  • Abstract attributes in Python

    - by deamon
    What is the shortest / most elegant way to implement the following Scala code with an abstract attribute in Python? abstract class Controller { val path: String } A subclass of Controller is enforced to define "path" by the Scala compiler. A subclass would look like this: class MyController extends Controller { override val path = "/home" }

    Read the article

  • Zend_Form and Liskov Substitution Principle

    - by blockhead
    A very common pattern I see (I'm picking on Zend Framework, only because I was dealing with it at the moment of this question), is something like this: class My_Form extends Zend_Form { public function init() { $this->addElement(); } } Zend_Form is not an abstract class, but is perfectly usable on its own. This seems to be "recommended" as place to "encapsulate" your forms into a nice class. Does this violate the Liskov Substitution Principle? Each subclass of Zend_Form will have a wildy different behavior than the base class. Would it be better to use composition for this, or am I totally misunderstanding this principle?

    Read the article

  • C++ overloading virtual = operator

    - by taz
    Hello, here is the code for my question: class ICommon { public: virtual ICommon& operator=(const ICommon & p)const=0; }; class CSpecial : public ICommon { public: CSpecial& operator=(const CSpecial & cs) { //custom operations return *this; } }; CSpecial obj; Basically: I want the interface ICommon to force it's descendants to implement = operator but don't want to have any typecasts in the implementation. The compiler says "can't instantiate an abstract class. Any help/advice will be appreciated.

    Read the article

  • Why is there no parameter contra-variance for overriding?

    - by Oak
    C++ and Java support return-type covariance when overriding methods. Neither, however, support contra-variance in parameter types - instead, it translates to overloading (Java) or hiding (C++). Why is that? It seems to me that there is no harm in allowing that. I can find one reason for it in Java - since it has the "choose-the-most-specific-version" mechanism for overloading anyway - but can't think of any reason for C++. Example (Java): class A { public void f(String s) {...} } class B extends A { public void f(Object o) {...} // Why doesn't this override A.f? }

    Read the article

  • Method return values and exceptions

    - by dnagirl
    I have an interface called iIncident which defines a single method when(). when() should return a DateTime object. I'm trying to decide what to do if $object->when() has no DateTime to return as might be the case just after an object is instantiated and before all its properties are set. My choices are: return false throw some kind of Exception return some default DateTime like '9999-01-01' My inclination is to go with an Exception since $object really can't act as an incident until it knows when it occurred. I don't want to return a default DateTime because it complicates comparisons and it's not true. And I don't really want to return false because then I have to check for it every time I call the method- but if that is the preferred method, I guess I will. Is throwing an exception the best way? And is there a predefined exception type I should use (none of the SPL ones struck me as particularly appropriate- but that might just indicate my lack of experience)?

    Read the article

  • Is there a design pattern for injecting methods into a class?

    - by glenn I.
    I have a set of classes that work together (I'm coding in javascript). There is one parent class and a number of child classes that are instantiated by the parent class. I have a number of clients of these classes that each need to add on one more methods to the parent or child classes. Rather than having each client inherit from these classes, which is doable but messy because of the child classes, I am having these clients pass functions into the parent class when they instantiate the main class. The main class creates the methods dynamically and the clients can call the methods like they were there all along. My questions are: is this a sensible thing to do? what would the design pattern be for what I am doing?

    Read the article

  • Address calling class

    - by Samuel
    I have an abstract class Moveable with the method abstract void move() which is extended by the class Bullet and the abstract class Character, and Character is extended by the class Survivor and the class Zombie. In Survivor and Bullet the move() method doesnt require any parameters while in the class Zombie the move() method depends on the actual position of the survivor. The survivor and multiple zombies are created in the class Gui. I wanted to access the survivor in Zombie - what's the best way of doing this? In Gui i wrote a method getSurvivor() but i don't see how to access this method in Zombie? I am aware that as a workaround i could just pass a [Survivor survivor] as parameter in move() and ignore it in Bullet and Survivor, but that feels so ... bad practice.

    Read the article

< Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >