Rule of thumb on what to make object PHP [closed] - php

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

Related

Dependency injection unneeded services [closed]

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 3 years ago.
Improve this question
Imagine we are using some Dependency injection and we use it in some controllers.
For example Laravel or any other framework with DI (doesn't matter the language in this case PHP).
Let's say we have this controller:
class UserController extends Controller
{
public function __construct(UserRepository $users, Mailer $mailer, Logger $logger)
{
$this->users = $users;
$this->mailer = $mailer;
$this->logger = $logger;
}
public function method1(){...}
public function method2(){...}
public function index(UserRepository $users){...}
}
Everybody say this is good design, but my question is this:
If the controller calls method1 and it uses only mailer for example, whats the point to construct the object with all the 3 dependencies. Isn't this not optimal even it doesn't take a lot of memory or performance ?
Somebody can think that this controller needs all of them but in reality if I call only method1 it will need only mailer.
If I try to inject the dependencies on the methods like "index" method, how can I do it because If i extend the same method and need different dependencies PHP will blow up because the method signatures are not the same.
What is the best way to handle this.
If I extract each method in separate controllers I'll have to do a lot of repetitions.
Thanks
There are a few things to consider:
First of all, when injection constructors are simple, it shouldn't matter that not all dependencies are used all the time. This shouldn't cause any measurable performance penalty, because the performance bottleneck will typically be caused by I/O.
If, however, your class contains many dependencies, and there are a lot of dependencies that are only used in some methods, it might be an indication that the methods on the class are not cohesive. That again could be an indication of the class violating the Single Responsibility Principle. In other words, the class might be too big, has multiple responsibilities, and if that's the case, it should be split into multiple smaller classes. Grouping class functionality around the concept of an entity (such as UserController does) is often a cause by SRP violations. Instead, a better solution typically is to group classes around functionality; e.g. DeleteUserController, PromoteUserController, BlockUserController, etc.

Clarification on design patterns in PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I know very little about design patterns out there. In fact i never worked with one yet, as i always went for raw coding. But i think its time to enrich my knowledge on design patterns out there. Specially i want to know more about Factory, Singleton & Strategy design patterns. I googled about them of course but I still not clear about their differences, how to implement them etc.
If anyone can suggest me some good document where i can read much more, that would be very much helpful.
Thanks in advance for helping.
https://sourcemaking.com/design_patterns is a very helpful website, with a lot of explanations and code samples, including PHP ones. I added very short summaries in my own words below. Disclaimer: because they summaries are very short, the may not be very accurate, but give you an idea on how the patterns compare.
Factory Method: https://sourcemaking.com/design_patterns/factory_method
In short: you have a separate class that is responsible for creating instances of a certain class. This is to make sure that a class is always constructed 'in the right way'.
Singleton Pattern: https://sourcemaking.com/design_patterns/singleton
In short: only one instance of a singleton class is possible, the class itself has a static class variable that stores the instance, and a static method that returns the stored instance, or create one if it is not yet created.
Strategy Pattern: https://sourcemaking.com/design_patterns/strategy
In short: if there are multiple ways to solve some problem, provide a set of classes that each contain one implementation to the problem and let the client decide which implementation to use.

Getter & Setter also for in class usage? [closed]

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
It is a bad way of programming, when i get access to my private/protected class members directly in the class via my getter/setter methods?
Alternative #1
<?php
class A {
private $myVariable;
public function getMyVariable() {
return $this->myVariable;
}
public function doSomething() {
$variable = $this->getMyVariable();
}
}
?>
Alternative #2
<?php
class A {
private $myVariable;
public function doSomething() {
$variable = $this->myVariable;
}
}
?>
Which way do you prefer? I think the first solution is more readable in constrast to the second one. Please let me hear your opinions.
Thanks in advance.
Since you are determined this is not a duplicate, I will copy the points from this response relevant to this case:
Encapsulation of behavior associated with getting or setting the property - this allows additional functionality (like validation) to be added more easily later.
Controlling the lifetime and memory management (disposal) semantics of the property - particularly important in non-managed memory environments (like C++ or Objective-C).
Providing a debugging interception point for when a property changes at runtime - debugging when and where a property changed to a particular value can be quite difficult without this in some languages.
Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.
Maybe you should think in another way: Why do we need getter/setter? They abstract direct access to a field. Even if the Getter does nothing other than setting a value, it can protect you later on. Changing a field to a Getter later is a breaking change, especially in PHP IDEs (badumm). So I think whenever you want to protect a field to prevent vulnerable/buggy code, use getter/setter.

Should you use static methods for helpers in PHP? [closed]

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

Is there any downside with using the Ghost Lazy Loading pattern in this way? [closed]

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
About the duplicate vote: This question is about the downsides of this approach, not about how to make this work; You can see it in this way: that question asks how to do something and the answer says something useful, however, I ask about the downsides of the answer.
TL;DR: will I encounter any technical difficulty by using this wrapper class later on? Why I haven't seen anything like this before?
I've been experimenting learning techniques for profiling recently and I found that creating the PDO instance is a place that could be optimized (~5ms). I don't need to use it in every call, however I'm creating it in every call from my code's structure. So, I just made this small class up:
<?php
namespace Library;
// Wrapper for \PDO. It only creates the rather expensive instance when needed.
// Use it exactly as you'd use the normal PDO object, except for the creation.
// In that case simply do "new \Library\PDO($args);" with the normal args
class PDO
{
// The actual instance of PDO
private $db;
public function __construct() {
$this->args = func_get_args();
}
public function __call($method, $args)
{
if (empty($this->db))
{
$Ref = new \ReflectionClass('\PDO');
$this->db = $Ref->newInstanceArgs($this->args);
}
return call_user_func_array(array($this->db, $method), $args);
}
}
To call it you only need to modify this line:
$DB = new \Library\PDO(/* normal arguments */);
And the type-hinting if you are using it to (\Library\PDO $DB).
It works flawlessly. It's also blazing fast (~0.2ms) when not using the PDO object and only introduces those ~0.2ms delay when using it (completely negligible). Now, I'm still learning about proper OOP, namespaces and general code structure, so I think I'm not qualified enough as to answer my own question yet:
Will I encounter any technical difficulty by using this wrapper class later on? Why I haven't seen anything like this before? therefore, why is this not more common or even default PDO behaviour?
Note: I intend to extend it furthermore by adding few more methods.
To answer your question: There is nothing wrong with this. This is a common optimization pattern, known as lazy loading, as you also mention in the comments.
While it could be implemented in different ways than what you have done here, your approach looks perfectly fine to me.

Categories