Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am building a MVC application in PHP, and am creating a Form class to generate a form that you can add elements to. Should I use static methods to generate the form, such as Form::generate(...) or in my view class where I declare variables to be used in a view file, should I instantiate the class and use it like $form->generate(...)? I have heard using static methods are bad because of testing, but I don't know. Thanks!
Beside the problem that PHPUnit doesn't support static mocks, the more obvious problem is that of loose coupling and dependency injection. It's completely fine if you have state-independent methods, but to strictly define those methods with the static keyword creates a hard dependency on the classname behind the double colon operator. (In fact, it's that hard dependency that makes the PHPUnit problem so tricky.)
I would agree that static methods have rather fallen out of favour except in certain applications such as:
Facade pattern, where the static methods hide a more complex API http://en.wikipedia.org/wiki/Facade_pattern
Factory pattern, where the static methods are responsible for creating and configuring object instances http://en.wikipedia.org/wiki/Factory_method_pattern
Utility type functions where the class is used almost like a namespace to group together related functions, but the functions themselves are basically procedural (examples could include string, date or price formatting functions)
I would start by creating one Form class that represents your form, and if necessary adding a factory helper which generates an instance of your form.
You might like to take a look at the Symfony form builder, their approach is elegant:
http://symfony.com/doc/current/book/forms.html#building-the-form
That depends, generally static methods wont maintain state, or in other words, you can't use dynamic properties within that class, or instantiate the class ( obviously ).
If you are using them as an OOP way of doing functions it should be fine, in fact I think Laravel uses a lot of them.
http://laravel.com/docs/quick
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have a little question, is setting values in factory method correctly ?
Something like this:
class ObjectFactory {
public static function create($config)
{
$object = new Object();
$object->setDependency(// something);
$object->setValue(// something);
return $object;
}
}
Is it correctly? Maybe it should be builder? How should i call it? ObjectBuilder, ObjectFactory, or maybe ObjectCreator?
Please explain me cases of creating object with some dependencies or initial values. I know it should be builder pattern but i heard that builder is something advanced than just returning object with few initial values or dependencies. So... what's the solution?
Firstly, it's not Builder Pattern. Builder is used when you have multiple ways to construct/config an object after instancing it, but those ways share common general steps. So you abstract those steps into an interface called Builder, then you have a class named Director which uses the Builder interface to call those steps in the order you want.
Secondly, your posted code is not about Factory Method Pattern in which a factory method is a method acted like a template in a base class, and will be implemented in derived classes.
The pattern in your code is typically called Factory Pattern where you just encapsulate a particular process of constructing an object into a method so you can easily reuse it.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have been trying to wrap my head around this for days now, and yet no answer.
I am currently building a website and I have some set of functions I have built. I later began to refactor them and put related function in a class, but at some point I got confused on whether some related function should also be grouped. From then I began to question myself that although PHP string functions are related why are they not grouped together as a class.
So what are other good reasons to classify a function?
And when are we not to classify some functions?
Note: I know a php String Class exist.
So what are other good reasons to classify a function? making a class of methods instead of a group of functions is not as much about grouping them together because they are related, as it is about scope, encapsulation, and instantiation.
when a method is in a class the developer has control over visibility and accessibility. This is also a consideration for the properties of the object.
unlike a group of functions, you can instantiate a class and define values for all of its properties and run its methods as allowed, and then do it again and again while each prior instantiation persists if you like. An example would be a game with a gun that shoots projectiles, each projectile may be an instantiation of the projectile class with its properties being position, velocity etc... each bullet has its own set of properties. There are an unlimited number of examples, many in common use.
I do not group functions into a class because of similarity of the functions, but due to functionality required of the class.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
When using Object-Oriented programming in PHP is there a simple rule of thumb on what should be made into an object or should you try to make the entire program using object-oriented code. I know this is quite opinion based but I can't seem to find any resources that could answer it for me.
Thanks.
I would suggest to read general oop concepts to get grip on that: http://oopsconcepts.blogspot.de/
What an object should be is largely language independent and whether your function should be an object or not fully depends on the context in what it is used.
Trivial code is usually not improved by making it object oriented.
In a scenario where your function is injected into something and must be replaceable it might make sense to make an object that implements an interface out of it.
Objects (or rather classes) should relate to a specific noun. For example, you might have a class called User, or Product. Functions generally are verbs. So you might have something like Product->Update().
Simple having a collection of unrelated functions in a generic Class does not constitute good OOP design. If the function is simply doing as you've advised, then it shouldn't have its own class.
A fairly standard pattern to follow with the kind of trivial, but global function your are discussing is to add it to a Utilty class.
In principle that is simply a class with public static member methods, that would normally be grouped by relation - exactly as you would a file of functions.
class MyFileUtility
{
public static function FileToArray($filePath) { // do stuff }
public static function ArrayToFile($array, $filePath { //do stuff }
...
}
$array = MyFileUtility::FileToArray('somefile');
Now you will use the methods of the Utility exactly as you would a function, but they are in a class, if it makes you feel better.
There are a couple of benefits:
Auto-loading will work, so long as you have configured it.
IMO You will generally be in a better / safer namespace situation.
If you like typing "::" You are well in :)
_____________ Edit _________________
Here is an explanation of a static Utility class added for clarity.
http://en.wikipedia.org/wiki/Utility_pattern
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am currently building a web app in php using Laravel-4, however, I suspect that this question is applicable to other languages and frameworks as well.
I have read about dependency injection and Facades and understand the necessary coding in each case. What I am not clear on is when you should use one over the other?
What the advantages/disadvantages or simply the reasons for using either dependency injection over the Facade design pattern?
Many thanks
Facades are used to make interactions with classes easier to read and use. It makes the code appear that you're using a bunch of static methods to interact with a class without instantiating it when in actuality you are calling methods on an existing object.
Dependency injection is used to, as the name implies, inject the dependencies of a class into the class. This is done through the constructor. You inject classes into another class to allow the class to use the functionality from the injected classes. This becomes powerful when you start injecting an interface into a class. Then you can create a class based on the interface and inject it into the class. This way, if you need to change the way the injected class works, you can create a new class based on the interface and inject it. Since you code is based on the injected interface, it will ensure that the class the received the injections will continue to work without needing to be changed.
This is most notable in Laravel 4 if you create a repository which is based on an interface for the Eloquent engine. You can inject that repository into a controller and use the methods on the interface to get the info you need. then if you ever want to switch to something like Redis, all you have to do is make a new class based on that interface that uses the Redis engine instead and then inject that class. The controller will never need to be changed.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a bunch of objects that I need to be able to serialize in JSON, PHP, whatnot. I have stuff such as a JSONSerializer, and clearly have serialize() available. Now what I still need is object specific logic to turn the objects into something that can be fed to JSONSerializer or serialize(). Basically either a primitive type or an array containing only elements matching this condition.
Two questions:
How do you call this step before serialization? "arrayification"? I'm thinking of giving my objects a toArray() method. I also want them to implement some interface that specifies this method? Anyone a better idea then "Arrayable"?
How can I go best about unserialization? I could have a static newFromArray method in each object. Not fond of static code though. Any opinions on a factory that can construct objects of a given type from their "arrayification"?
Note: This needs to work with PHP 5.3.
The Symfony Serializer Component provides one answer to both questions. It calls the step from object to array "normalization" and the reverse "denormalization".
For construction of "deserializers" or "denormalizers", I have found creating an abstract factory very useful. It solves the construction problem, and can isolate the user from even knowing which exact deserializer they are using. An example of this is this deserializer factory which is based on the Serialization component.