Why people use singletons in their PHP framework - php

Ok guys I am struggling to understand why there is a need of singleton.
Let's make a real example: I have a framework for a my CMS
I need to have a class that logs some information (let's stick on PHP).
Example:
class Logger{
private $logs = array();
public function add($log) {
$this->logs[]=$log;
}
}
Now of course this helper object must be unique for the entry life of a page request of my CMS.
And to solve this we would make it a singleton (declaring private the constructor etc.)
But Why in the hell a class like that isn't entirerly static? This would solve the need of the singleton pattern (that's considered bad pratice) Example:
class Logger {
private static $logs = array();
public static function add($log) {
self::$logs[]=$log;
}
}
By making this helper entirely static, when we need to add a log somewhere in our application we just need to call it statically like: Logger::add('log 1'); vs a singleton call like: Logger::getInstance()->add('log 1');
Hope someone makes it easy to understand for me why use singleton over static class in PHP.
Edit
This is a pretty nice lecture on the singleton vs static class for who is interested, thanks to #James. (Note it doesn't address my question)

Many reasons.
Static methods are basically global functions that can be called from any scope, which lends itself to hard to track bugs. You might as well not use a class at all.
Since you cannot have a __construct method, you may have to put an init static method somewhere. Now people in their code are unsure if the init method has been called previously. Do they call it again? Do they have to search the codebase for this call? What if init was somewhere, but then gets removed, or breaks? Many places in your code now rely on the place that calls the init method.
Static methods are notoriously hard to unit test with many unit testing frameworks.
There are many more reasons, but it's hard to list them all.
Singletons aren't really needed either if you are using DI.
A side note. DI allows for your classes not to rely on each other, but rather on interfaces. Since their relationships are not cemented, it is easier to change your application at a later time, and one class breaking will not break both classes.
There are some instances where single state classes are viable, for instance if none of your methods rely on other methods (basically none of the methods change the state of the class).

I use singletons, so I can tell you exactly why I do it instead of a static function.
The defining characteristic of a singleton is that it is a class that has just one instance. It is easy to see the "just one instance" clause and forget to see the "it is a class" clause. It is, after all, a normal class object with all the advantages that that brings. Principly, it has its own state and it can have private functions (methods). Static functions have to do both of these in more limited or awkward ways.
That said, the two complement each other: a static function can be leveraged to return a singleton on the same class. That's what I do in the singleton I use the most often: a database handler.
Now, many programmers are taught that "singletons are bad, mm'kay?" but overlook the rider that things like are usually only bad when overused. Just like a master carver, an experienced programmer has a lot of tools at his disposal and many will not get a lot of use. My database handler is ideal as a singleton, but it's the only one I routinely use. For a logging class, I usually use static methods.

Singletons allow you to override behavior. Logger::add('1') for example can log to different devices only if the Logger class knows how. Logger::getLogger()->add('1') can do different things depending on what subtype of Logger getLogger() returns.
Sure you can do everything within the logger class, but often you then end up implementing the singleton inside the static class.

If you have a static method that opens a file, writes out and closes it, you may end up with two calls trying to open the same file at the same time, as a static method doesn't guarantee there is one instance.
But, if you use a singleton, then all calls use the same file handler, so you are always only having one write at a time to this file.
You may end up wanting to queue up the write requests, in case there are several, if you don't want them to fail, or you have to synchronize in other ways, but all calls will use the same instance.
UPDATE:
This may be helpful, a comparison on static versus singleton, in PHP.
http://moisadoru.wordpress.com/2010/03/02/static-call-versus-singleton-call-in-php/

As leblonk mentioned, you can't override static classes, which makes unit testing very difficult. With a singleton, you can instantiate a "mock" object instead of the actual class. No code changes needed.
Static classes can have namespace conflicts. You can't load 2 static classes of the same name, but you can load 2 different versions of a singleton and instantiate them under the same name. I've done this when I needed to test new versions of classes. I instantiate a different version of the class, but don't need to change the code that references that class.
I often mix singletons and static. For example, I use a database class that ensures there is only 1 connection to each master (static) and slave (singleton). Each instance of the db class can connect to a different slave, if a connection to the same slave is requested, the singleton object is returned. The master connection is a static object instantiated inside each slave singleton, so only 1 master connection exists across all db instantiated objects.

Related

Advice regarding object oriented design and wrapper methods

I have a State class that includes configuration as well as some state-specific methods. I also have a Factory class that I inhertit my MVC classes from that also has a reference to this State object. This makes sure that all of my MVC objects have specific State-related functionality. For example, my State class includes methods for setting and reading cache or sessions.
My Factory class has a number of methods that are simply wrappers, like this:
public function myFunction($data){
$this->State->myFunction($data);
}
The idea is that these methods are defined in Factory, but are actually executed by State object. This allows me to call:
$this->myFunction(); rather than the longer one that includes State in it, when writing code.
I don't know enough about how PHP works internally, but is this efficient? My thought process has been that since I usually only have one instance of State object, then having method wrappers in my Factory class is better, because otherwise those methods would include a lot of code that is not used most of the time. But I am not sure how PHP works internally.
At times I can have dozen objects that have the parent Factory class and all of them reference the same State object. Is it efficient to have wrapper methods defined in Factory that simply call methods of State, rather than deal with State directly? Or am I just adding additional overhead to the whole system?
My idea was that if Factory is simply a class that is inherited and includes wrappers for a lot of functionality, then I can streamline development more efficiently. Does it save memory if the class that you inherit from has wrappers as opposed to fully defined code in methods?
No, such wrapper has not performance benefit. Actually, what you get this was is an extremely minor loss of performance.
What's more important, this way you are hiding dependencies, which might make it harder to maintain the code.
Few thoughts on your topic
I get the impression, that you are doing it all wrong tm. Here are the issues, that I have with what you wrote in the question:
Is the State class responsible for configuration OR "state specific methods"?
There is such thing as SRP, which states, that every class should have a single responsibility. You could also say, that every class should have only one season to change.
Why do your "MVC classes" inherit from Factory class?
In object oriented code, the keyword extends represents an is-a relationship between classes. It's OK to have class Oak extends Tree, but when you write class User extends Table, it is complete insanity .. and kinda insulting. This is covered by LSP (for a simplified explanation: look here).
You have misunderstood the purpose of Factory pattern.
Factory is a creational pattern. This means, that the purpose of factories is to return object instances. Instead of inheriting some methods, which provide access to State instance, you should inject it in each of created structure.
class Factory
{
protected $state = null;
public function __construct( $state )
{
$this->state = $state;
}
public function create( $name )
{
$instance = new $name( $this->state );
return $instance;
}
}
This will have the added benefit that all the structures, which Factory instance created, share the same State instance.
Seems like you are trying to have global state thought-out your codebase
If every in your application need access to instance of State, then something is deeply wrong with the whole architecture. You end up with situation where a single object exists in all layers, thus causing a major leak in abstractions. You basically are just hiding a global variable.

I have a class with 14 static methods and 4 static properties - is that bad?

I have been writing a PHP class that is exactly 450 lines long and it contains 14 static methods and 4 static properties as well as 6 constants (and private __construct() and __clone()).
I am wondering here is that am I doing something wrong, is my class evil?
When you use the class, you always call a single method like:
MyClass::coolMethod();
and then you leave it alone altogether so it feels that it would be stupid to make it constructable?
There's really not much point in constructing objects out of it, because it is more like a tool that contains a few methods that you can just call directly.
Actually, out of those 14 methods, 7 of them are public -- the rest are private for the class to use.
You should avoid static as much as global.
Statics give you the same disadvantages globals give you. Whenever you are using any class methods, you are hardcoding a dependency on that class into the consuming code. The result is less maintainable tightly coupled code. This can easily be avoided by avoiding statics altogether and a disciplined use of Dependency Injection.
You cannot inject and pass around static classes, so for instance when you have to unit-test them, you cannot mock them (or at least only with some effort). It's just plain painful. Static methods are death to testability.
Also, keep in mind that classes should do only one thing. They should have a single responsibility. Go through your class to see if there is stuff in there that's better placed somewhere else to avoid writing a God Class.
It depends on the purpose of this class. If the methods are mostly incoherent in terms of data, this is a perfectly valid solution of grouping functions (now methods). This is a very bad idea if you need to share values between functions, since that would be more than a simple list of functions, grouped under a common name. Namespaces are another option, but if you're using a PHP-version lower than 5.3, this is probably the best solution.
This is like saying, "I have a house with four bedrooms. Is that bad?"
Static methods are neither good nor bad. Having fourteen methods is neither good nor bad. Having fourteen static methods is, by extension, neither good nor bad.
If in your fourteen methods you're going to great lengths to simulate object instances, or to simulate inheritance, then something has gone horribly wrong. PHP will let you create instances, and supports inheritance, so it would be silly to try to simulate them any other way.
But if you're just using your class essentially like a namespace, where the functions and data all work together but there are no individual instances of the class to contend with, there's absolutely nothing wrong with that.
Not bad. However, with all those static props, you might want to consider making this a singleton.
Here is some singleton code I am using in the framework I am building. You can tear it apart and make it the sole public method for your class that returns the one version of itself.
class ClassName {
function getInstance()
{
static $instance;
if (!isset($instance))
{
$instance = new ClassName();
}
return $instance;
}
}
You would use this, then, by doing ClassName::GetInstance()->othermethod();
The class can then have tons of private values and otherwise gain all the nice things you have with an object.
I would say that no, it isn't bad. In fact that was the only way to fake certain behavior before. It was for instance a way to fake namespaces. One could encapsulate functions in static classes instead of having them "out in the free". So allot of php developers are familiar with this and it won't actually confuse most people. What you SHOULD try to do nowadays though is to make use of PHP's "new" namespace feature and if needed combine it with a singleton pattern if you actually need to store data in an object format. You could just as well have a "global" variable contained in your namespace and that could work fine at times to. But take a look at namespaces and see if that fits you in any way and after that see if singleton pattern might match your specific needs.

Singleton class and using inheritance

I have am working on a web application that makes use of helper classes. These classes hold functions to various operation such as form handling.
Sometimes I need these classes at more than one spot in my application, The way I do it now is to make a new Object. I can't pass the variable, this will be too much work.
I was wondering of using singleton classes for this. This way I am sure only one instance is running at a time.
My question however is when I use this pattern, should I make a singleton class for all the objects, this would b a lot of code replication.
Could I instead make a super class of superHelper, which is a singleton class, and then let every helper extend it.
Would this sort of set up work, or is there another alternative?
And if it works, does someone have any suggestions on how to code such a superHelper class.
Thank you guys
I can't pass the variable, this will be too much work.
Are you sure though? People tend to overestimate the effort of passing around dependencies. If you do it in the constructor, it's usually fairly simple to do.
That said, you can put shared functionality in the global scope, in different ways in php. The simplest is to use a global function. Eg. a function that doesn't belong to any class. Another option is to use a static class method. These two a very similar; except for their syntax, they essentially have the same properties. A slightly looser coupled solution is to put the functionality as a method on an (abstract) base class, that your concrete class extends from. This shares the functionality between all child classes.
Common for the above-mentioned solutions is that they have a compile time coupling. You can't change the dependency at run time, which makes your application rather rigid. Their main benefit is the low level of complexity they carry.
If you want a looser coupled application, you can try to replace the hard dependency with a variable, to give a level of indirection. The simples is to create an object and make this shared globally throughout the application. There are a number of ways to do this in PHP, such as a singleton or simply a variable in the global scope (You can access this with the global keyword, or through the $GLOBALS array).
While global variables offer a level of indirection, they also tend to introduce a lot of complexity, since they make it very hard to figure out which parts of the application that depends on each other. For this reason, they are often avoided by experienced programmers. This is especially true if the variable has state; The problem is less prevalent if the shared object is stateless.
The only way to avoid the perils of global variables, is to use local variables instead. Eg. To pass the dependencies around. This can be a bit of a hassle, but in my experience it's often not as big a problem as it's made out to be. At least, the benefits often outweigh the problems. That said, there are techniques to easy the pain; Notably dependency injection containers, which are automatic factories that take care of all the wiring for you. They come with their own level of complexity though, but for larger applications they can certainly be a good solution.
Look into the factory pattern and dependency injection.
http://www.potstuck.com/2009/01/08/php-dependency-injection/
You can't extend a singleton class. Remember in singleton class we make the constructor private so if a constructor is private than how could you extend this class? We all know what we create an object of a class we call its constructor and in child class constructor it implicitly called the parent constructor. So in this scenario a private constructor can't be called in the child class.
While sometimes necessary, singletons are evil (because they're global state). Try to avoid them if you can help it.
EDIT: If you can't avoid singletons, at least parameterise the reference to that state. In other words, in a class, pass in the singleton to its constructor or those methods that use the singleton.
Simply making references all over your codebase to your singleton will compromise your ability to test classes in isolation.
If your singleton's stateful, your tests will suddenly become stateful, and your tests can start "cascade failing" because their preconditions become corrupted by earlier tests failing.

Correct Implementation of Virtual Functions in PHP?

at my working place (php only) we have a base class for database abstraction. When you want to add a new database table to the base layer, you have to create a subclass of this base class and override some methods to define individual behaviour for using this table. The normal behaviour should stay the same.
Now I have seen many new programmers at our company, who just override the method for the default behaviour. Some are so "nice" to put in all the default behaviour and just add there individual stuff where they like it, others kill themself trying to use the baseclass and their inheritor.
My first thought to solve this problem, was thinking about abstract methods that should be overriden by inheriting classes. But beside other arguments against abstract methods, "abstract" just does not show why the baseclass can't be used by its own and why these function should be overriden.
After some googling around I didn't find a good answer to implementing "real" virtual functions in php (just that there is a virtual function, that nearly kills all hope of a concrete implementation).
So, what would you do with this matter?
In PHP all public and protected functions are "virtual". You can prevent functions from being overriden by prepending the final keyword. (Or by making them private, but this is probably a bad idea).
In the design of the baseclass I would think of behaviors that subclasses would want to affect.
I would for example create empty functions like before_update() and after_insert().
function after_insert() {
// Virtual
}
Which the baseclass will call when an update/insert event occurs.
Maybe an is_valid() function which always returns true in the baseclass, and use the commentblock to describe what the consequences are when a subclass return false.
Hopefully this would give you some inspiration.
You can always use the "final" keyword to prevent some of the classes functions from being overridden if people are using the class in the wrong way.
It sounds to me like they are unable to acheive certain functionality hence overriding the methods. You may need to take a look at the design of your classes.
Without an example of the implementation of your base class, it's hard to give concrete info. But a few things come to mind:
Database abstraction is complex stuff to begin with. I understand that you want to keep it lean, clean and mean, but I think it's pretty darn difficult. You really have to take a thorough look at the specs of different DB engines to see what parts are general and what parts need specialization. Also; are you sure you don't have DB abstraction mixed up with the Table Data Gateway pattern, as you are talking about adding DB tables by extending the base class?
The methods of your current base class might be doing too much and/or are not general enough to begin with, if the extended classes are bending over backwards too keep it clean. Maybe you should break the base class interface methods up in smaller protected methods that are general enough to be reused in the overriding methods of the extended classes? Or vice versa: maybe you should have hooks to overridable methods in your interface methods.
Following from point 2: What's wrong with having an abstract class with some general implemented methods, and let your vanilla class (your base class) and other classes inherit from that?
Lastly, maybe you should just enforce an interface to be implemented, in stead of extending the base class?

correct use of 'construct' when designing classes

I am new to object oriented programming and writing some of my first classes for a PHP application.
In some of the simpler classes, I declare a function __construct(), and inside of that function, call certain class methods. In some cases, I find myself instantiating the class in my app, and not needing to do anything with the resultant object because the class's __construct() called the methods, which did their job, leaving me nothing left to do with the class.
This just doesn't feel right to me. Seems goofy that I have a new object that I never do anything with.
Again, I'll stress this is only the case for some of my more simple classes. In the more complicated ones, I do use class methods via the object and outside of __construct().
Do I need to rethink the way I coding things, or am I ok?
Well, the constructor is used to create a new instance of a class, and to do any necessary setup on that class. If you're just creating the class and leaving it, that does seem a bit of a waste. Why not, for instance, use static functions in the class as an organizational tool and just call them(or a function that calls them) instead of constructing a new instance that you'll never use?
This just doesn't feel right to me. Seems goofy that I have a new object that I never do anything with.
Yes, that should raise a red flag.
In general, you should not let constructors have any side effects; They are meant for initialising the state of the object - not for anything else. There are of course exceptions to this rule, but in general it's a good guide line. You should also abstain from doing any heavy calculations in the constructor. Move that to a method instead.
Side effects are many things - Changes to global variables or static (class) variables; output to the environment (For example calls to print(), header() or exit()); calls to a database or other external service and even changes to the state of other objects.
A side effect free function is also called a "pure" function - as opposed to a procedure, which is a function that has side effects. It's a good practise to explicitly separate pure functions from procedures (and perhaps even label them as such).

Categories