I've always been told be be very careful when creating static classes as they have a tendency to be overused by less skilled programmers.
I'm currently writing a session class in PHP to keep track of a user on the site.
A session seems like it would make sense being in a static class because there is only ever going to be one of them right?
I used to work in a CMS that had a factory which created a session object but then stored the instance and when ever a new session was requested ( MyFactory::getSession() ) it would return the previously initialised one. Is there any advantage to this?
Thanks!
No, classes should never be static, if you are doing object oriented programming. That applies to factories too. The Static factory method pattern ( which you showed in the example ) is considered a bad practices, because it violates SRP.
The static variables are just globals by different name and static methods are namespaced function, where the namespace just happens to look like class.
If you need multiple object to use same session instance, then you should provide them all with it. Either directly or by using a factory.
class ObjectFactory
{
protected $session;
public function __construct( $session )
{
$this->session = $session;
}
public function create( $name )
{
return new $name( $this->session );
}
}
You pass instance of this factory to any object, which would need create structures, that use session. You just create the objects with this factory and they all will be initialize with same session instance.
In more simplified example you can just pass the session to each object manually:
$session = new Session;
$user = new User( $session );
$article = new Document( $session );
Both $user
and $article
instances now will share the same session instance.
For more information, watch the following presentations:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With