What's the difference between Singleton and Registry design pattern - php

I have some confusion between those two patterns:
singleton
Check if the instance exists return it, or create a new one.
Registry
Check if the instance exists return it, or create a new one and store it.
What the difference between them?

Both are about instance control. The difference is that Singleton allows only one instance of a given class while Registry holds a 1-1 map of keys to instances. Typically, the key is (or represents) a class and the value is an instance of that class.
For example, Code Igniter framework holds a registry with an instance of each library/model/controller/helper you load and returning those same instances every time.

Level of access and complexity
One fun filled caveat I always love, is that a registry pattern is utilizing a singleton to store/retrieve a dynamic list of objects.
Singleton Pattern
Singleton pattern is a pattern by which you establish a single point of access and methodology. While many people believe it is an anti-pattern, I assure you it is only because of the level they work at and type of programming they do.
Singleton patterns are used at lower levels to manage strict resources. For instance, while most languages have libraries that wrap keyboard input, it is effectively a singleton pattern as it has very strict input/output and only one can exist, regardless of how many keyboards you have.
Testing Singleton patterns
One of the reasons people feel singleton patterns are anti-patterns, is they are in general untestable in a unit test system. It is not possible to even mock a singleton in most languages, as it is fixed to a specific identity.
For this reason the singleton should be minimal, and a wrapper used to interface it.
You can then inject the wrapper and it can be mocked to used a fake singleton mock.
Registry Pattern
The registry pattern is where you establish a single point of access, but not a single methodology. This very registry access will have at least 3 methods: put, find, and delete. These methods rely on a singleton pattern to work.
The map is testable, as it is not isolated to your use, and while the registry itself is not actually unit testable in connection to the units that consume it, you can utilize mocks of everything the registry is intended to contain.
However, if you utilize IoC in a given architecture consuming it, you can inject the registry from the container registry, allowing a mocked registry to be injected instead.
Final note
Inversion of control is vastly popular these days, however big parts of it are often not learned or ignored. Some frameworks boil it down to mostly the factory pattern for most things, abstracting the rest away.
I would strongly encouraging most to toss out everything they know about IoC.
Then learn SOLID.
Afterwards read a book on design patterns for OOD. (Note: If the book has pros and cons of the patterns, it is good, if it does not show the cons, I would be very wary of the book.)
While these terms were coined relatively recently, the principles were learned in one manner or another early on, and in fact became the basis of Object Oriented Design.
The patterns most object oriented developers use successfully are all based on SOLID principles.
A reference to SOLID, that is laid out and summed up.
https://www.digitalocean.com/community/conceptual_articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design
As a final suggestion: Even if you are not an object oriented developer, it is very useful to learn SOLID and OOD, as must system architecture follows similar patterns when integrating a system together.
In addition I would not suggest you assume that one language/pattern/philosophy fits best for all needs. Keep learning, keep an open mind. The more you know, the better the solutions you can bring to the table.

A Registry differs in that its principal purpose is to allow you to navigate to associated objects. See Martin Fowler.

The main difference between registry and singleton is that singleton allow us to create a single instance of a class at a time, whereas registry allows us to create multiple instance of the same class.

Registry Definition: When you want to find an object you usually start with another object that has an association to it, and use the association to navigate to it. Thus, if you want to find all the orders for a customer, you start with the customer object and use a method on it to get the orders. However, in some cases you won't have an appropriate object to start with. You may know the customer's ID number but not have a reference. In this case you need some kind of lookup method - a finder - but the question remains: How do you get to the finder?
A Registry is essentially a global object, or at least it looks like one - even if it isn't as global as it may appear.
Singleton Definition: Sometimes it's important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.
Based on these definitions their usage are completely different.

Related

Reusing Complex Object Instances in PHP

Is there a reasonable way to ensure that you aren't unnecessarily re-instantiating expensive object instances in PHP?
I have an application that deal with US States. Each state is an instance of the USState class. I'd like to ensure that the application only ever has one instance of each state object, although they are used in many places throughout the application.
I looked into the singleton pattern, but that seems to be used for times when a class only has a single instance - here there are 50 instances, but no more.
I guess I could put them in the global scope and always refer to them that way (global $california), but that seems wrong.
I would use Service Locator Pattern or Dependency Injection, which is provided by your framework. Usually I go with Zend Framework, but not knowing your circumstances, I assume you have no framework at all. In this case I would suggest very simple Dependency Injection Container, but that would add a dependency on DIC itself. Pimple is one of them.

understanding factory design pattern

I was learning about factory design pattern in php. From what i understand, this pattern is useful in cases where we have a bunch of classes, lets say, class_1, class_2, class_3 etc.
If the particular class which has to be instantiated is known only at runtime, then instead of using the new operator to create the objects for these classes we create a factory class which will do the job for us.
The factory class will look somewhat like this:
class Factory
{
// $type will have values 1, 2, 3 etc.
public function create_obj($type)
{
$class_name = "class_".$type;
if(class_exists($class_name))
{
return new $class_name();
}
}
}
My question is what is the advantage in using a factory class here? why not just use a simple function instead of a class which is going to complicate things?
The method in your code snippet is not a factory method, but merely a helper method which does a well-known reflective task: instantiates a class based on its name. This is exactly the opposite of what a Factory pattern is for: creating objects (products) without specifying the exact class of object that will be created.
As explained in Wikipedia:
The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate."
You are probably confused by the last PHP example in the Wikipedia article on Factory pattern, and yes, it is a bad example. Check the Java example just above that for a meaningful example (whoever tried to convert that to PHP missed the whole point). The Java example returns a file reader based on its extension, and that is exactly the use case for a factory pattern. Creating your own personal "rule" that certain classes need to have a certain name prefix is most likely a bad design decision.
At the basic root of the question you could use a simple function to accomplish the goal. Where this breaks down is the programmer best practice where you want Low Coupling, High Cohesion.
The function itself plays a special role in your application design and to put it alongside other functions with different roles and purposes is non-intuitive to maintain and read. Remember, patterns are used to simplify common problems that are faced (almost) universally through project domains and as a result they tend to be segmented from the rest of the code base in order to help differentiate them.
Additionally, by placing the pattern in its own class any classes that need to use it do not need to know the class structure of class_1/2/3/etc. and instead only need to refer to the parent class allowing you to create further classes down the line, modify the pattern accordingly without needing to resolve dependencies and links in your remaining code. This ties back to the low coupling.
The concept is that you design to an interface then you can swap out the class later.
Forget this pattern for a minute an consider this:
if (type == "manager")
employee = new manager();
else
employee = new employee();
employee.name = "myname";
In this case employee and manager both inherit from the same class. After the if statement you can treat them like people and you are abstracted from their actual implementation. Instead of having if statements all over the place, you can implement the factory pattern. If you only have a couple the pattern is probably overkill. If you want to easily extend the program in the future, consider a pattern.
Another important reason for using the Factory Pattern is to consider what happens to your code when you have to add classes to your design & code.
If you're not using a Factory Pattern, your code is going to be increasingly tightly coupled, you'll have to make changes in many different places. You'll have to ensure that every place you have to touch the code is coordinated with all of the other (tightly coupled) places you'll have to touch. Testing becomes much, much more complicated, and something is going to break.
The Factory Pattern gives you a way to reduce coupling and helps you to encapsulate responsibilities into just a few places. With a Factory Pattern, adding additional classes means touching the code in fewer places. Testing (constructing test cases as well as running tests) is simplified.
In the real world, most code is complex 'enough' that the benefits of the Factory Pattern are clear. Changing, refining and growing the object model, making testing as complete and rigorous as possible in the face of rapid change, and ensuring that you're making your code as non-rigid as possible (all while realizing that multiple people are going to be working on it over the course of months/years) -- the Factory Pattern is usually a no-brainer.
With a trivial example, it can be hard to see the advantages of using the Factory Pattern. (And if your code really is trivial, then the pattern probably won't buy you much.) That's a problem with many examples I see when I search for it on the web -- the examples tend to focus on 'you can determine the class at run-time!' and are simplistic.
Here's one example that's not too trivial, and I think gets people about thinking of all of the possible benefits of the pattern:
A presentation on the Factory Pattern by Bob Tarr (pdf). (It's example 2, starting about page 10.) Imagine you're writing a maze game where a person has to explore a maze and all the rooms in a maze. Your object model include a Maze that consists of things like Doors, Rooms, Walls, and there's a Map that also has to keep track of them all. Simple enough. But what happens when you start adding Enchanted Rooms and Enchanted Doors and Magic Windows and Talking Pictures and Twisty Little Passages? You're going to end up with a lot of classes to represent everything; you want to make sure that you have to change (touch) as little code as possible when you add a new class. And you don't want to have to modify the code in the Map class, for instance, each time you add a new class: you want to keep the classes focused on what they should really be responsible for.
Think not just about what gets instantiated at run time, but also about code complexity.
He also gives an example of using the Factory Pattern (a Factory Method, specifically) with UI components -- where the Factory Pattern turns up a lot. (For a beginner, or someone who has never dealt with UI code, I don't think that example is quite as clear.)
Remember that most coding is done on existing code: most time is spent modifying code that's already there. You want to be sure that your code will be able to handle changes without being fragile. Reducing coupling and encapsulating responsibility will go a long way in making it so.

In PHP what means: factory, instance and observer?

In PHP, what means: factory, instance and observer?
Thank you!
observer and factory
observer and factory are two design patterns within object oriented programming. gang of four (or gof) are usually attributed the creation of these patterns. they have a book, i believe it's with implementations in c++. i haven' read it, i heard it was kind of heavy to read. however, i did read "head first design patterns", and that's a really good book! still high level stuff though, maybe for someone who has been programming for a year or so.
instance
an instance is something concrete. instance is to class what an employer is to its profession. the profession is a way of describing something that workers with that profession does. a job description so to speak. the worker then actually performs the work in question.
correlation between factory and instance
being a worker of a factory profession means that you have the responsibility of creating workers of some other, probably more complex, profession. or maybe the profession itself isn't very complex, but the process of creating a worker of that profession is complex.
important final note
all these terms are valid and interesting within all object oriented languages, like for example php, java, c# and c++, and many more.
It's not relative to PHP only. What those words mean are "design patterns" concept, that is, a method of organizing code that achieves a series of properties, such as loose dependency, ease of reuse and test.
I suggest you a book colloquially called Gang of four. It explain basic design patterns and it's a classic in its topic.
Factory and Observer are design patterns.
a class is a blueprint of an object.
an instance is an created object of a specified class.
Blatantly copied from Wikipedia:
The factory pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects.
https://en.wikipedia.org/wiki/Factory_pattern
Example code for a factory can also be found in the PHP Manual on Patterns
The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
https://en.wikipedia.org/wiki/Observer_pattern
PHP has a native interface to implement Subject/Observer patterns in SPL
An instance is an object derived from a class definition, e.g.
$instance = new StdClass;
It means the same as in any language support some flavor of OOP. A class with a very specific responsability.
Look here for more details:
http://en.wikipedia.org/wiki/Factory_pattern
http://en.wikipedia.org/wiki/Observer_pattern
Same thing it means everywhere else. Factory and Observer are design patterns. I'm not sure I can describe what instance means without using the word instance in the definition... Or Instantiate, which is just the word instance in disguise.
factory and observer are design patterns used to solve a few common OO problems. instance is an object of a class which will be used to access methods within that class ex.
$userObj = new User();
$userObj is an instance of the User class.
for more information on design patterns check this link out
http://www.fluffycat.com/PHP-Design-Patterns/

Should all Front Classes use singleton?

Consider Martin Fowler's Patterns Of Enterprise Application Architecture, and the pattern of Front Controller: http://martinfowler.com/eaaCatalog/frontController.html
Apparently, it uses the singleton pattern. Well, I have a package of classes in php application that work together (like Zend's Controller Package) and there is one class that makes them all usable and since it resembles much of Front Controller's concepts, I named it PackageName_Front. But it shouldn't be a singleton class (as opposed to Front Controller), so do I still let it have the name Front? If not, what do I name it?
Since it's a quite big package, I just need it to follow conventions as much as possible (not in a dogmatic way!) so it would be readable to other developers.
More info: It's not anything related to controllers. It's just an object that works like Zend_Form (which consolidates use of all the other objects like Zend_Form_Element_X and Zend_Validate into one object) But I can't just name it PackageName. It has to be PackageName_Something, and I'm just not sire what Something should be. Maybe "Handler"?... I just wanna make sure when someone reads it's name, doesn't get confused about it's role in the whole Package :)
Apparently, it [FrontController] uses the singleton pattern.
FrontController does not have to be implemented as Singleton. The book does not suggest anything like this. The example in the book uses a Servlet for the Handler.
Just because a class will only be needed once in an application doesnt justify it's implementation as a Singleton. It's missing the purpose of the Singleton which is to enforce a class can only have one instance and provide global access to it. If you need a particular instance only once, consider Just Create One instead.
Many people nowadays (including Erich Gamma of GoF fame) view the Singleton as a code smell and discourage it's use. In a shared-nothing-architecture the Singleton can only restrict instances inside the current request anyway, so the use in PHP is limited. Global access to an object can be achieved without the Singleton pattern, either through the (evil) global keyword or static methods. Global access always creates unneeded coupling. The better way would be to use Dependency Injection, which has the added benefit of providing less coupling and thus better maintainability.
so do I still let it have the name Front? If not, what do I name it? Since it's a quite big package, I just need it to follow conventions as much as possible (not in a dogmatic way!)
There is no such convention about naming classes Front classes to my knowledge. What you describe could be a Facade or a Gateway though. Also, are you sure you cannot name the class after the PackageName? After all, the Zend_Form package has a Zend_Form class, too.
Just from a purely design view, it sounds like you're using that PackageName_Front as a Facade when you say:
there is one class that makes them all
usable
Fowler's implementation of the pattern says:
The Front Controller consolidates all
request handling by channeling
requests through a single handler
object
This insinuates that a Singleton might be used to implement the Front Controller class, but it certainly doesn't constrain it to use it. He doesn't explicitly mention it though.
I don't think it's important whether or not its a Singleton. Just makes sure its the sole channel for requests, and you'll have successfully used the pattern. :)
The idea behind the singleton pattern is to make sure there is only one instance of an object that is supposed to only exist in a single instance. The front controller falls very well into this category, so it would, perhaps, be wise to make it follow a singleton pattern.
If, however, your code will always make sure it calls the constructor only once, then there is room for your non-singleton pattern object.
My 2 cents here, since I'm not any book author or something.

Is it ok to wind up using mostly static classes?

I'm currently rewriting an e-shop - but only the client side, i.e. the CMS remains mostly in tact. I am not using a pre-built framework, as the system has to retain backwards compatibility with the CMS and I have to have full freedom of the structure of code.
The new system is purely MVC based and I have a Bootstrapper which loads controllers based on the current uri and the latter use models for the real work - both with sessions and the database.
tl;dr It's my first project without a pre-built framework.
I am very inexperienced when it comes to design patterns. I know how do most of the popular ones work but have had never put them to use.
Now I am suspecting code smells because all of my models are classes that consist purely of static methods. I can find no advantages of doing them in a different manner. I routinely need some of the methods in various places through out the code. I.e. I need to fetch the logged in user in the main layout, check user rights to see current page in the bootstraper, display user panel by the controller. I'd need to re-instantiate an object each time or keep a global one if I wasn't using statics. There also won't be a need for more than one such class at a time.
I must be missing something, because even though I use OOP, some my classes are just meaningless containers for their methods (and sometimes a couple of private variables). I could have just been using PHP4 and simple functions.
Any comments or advice would be highly appreciated.
EDIT: in spite of all these educated answers, I remain unconvinced. Even though it's most probably because of my lack of experience, I still don't foresee anything going wrong with the current setup. I mean I don't even fathom a situation where I'd have any inconveniences due to the code architecture as it is now. I hope I don't get a harsh lesson when it's too late to change anything...
You are right, it's a code smell and everybody will tell you it's baaaad.
So here I suggest rather to make a self-assessment of the severity of the problem:
Do you have classes with many getter and setter?
Are your static functions like the one below?
If yes, try to move the logic in the class MyClass that will be already way more OO. That's a classic mistake from procedural/scripting world.
static void myMethod( MyClass anObject )
{
// get value from anObject
// do some business logic
// set value of anObject
}
Do you have a lot of global state, such as data you fetch from the current session?
If yes, make an assessment whether you want to change it. The OO way would be to pass the session down the call chain. But in practice, it's convenient to access the session as a global object. But it impedes testability. Try to remove some global state and turn that into regular object that you pass and manipulate in methods.
Make this assessment, and try to identify utility classes, services classes and the business objects. Utility class are helper classes with utility methods (e.g. formatting, conversion, etc.) which can be static. Service class do some business logic but they should be stateless and one instance suffice. Business objects are user, products, article, etc. is where you must concentrate your effort. Try to turn plain data into objects with embed some behavior.
Have a look at should entity be dumb. Even if it's for java, the concepts are general.
EDIT
Here is my analysis based on your comment:
You don't have a domain model with entities. You manipulate the database directly.
What you call your model, is what I call services and is where you perform the business logic that manipulate data. Service classes are stateless, which is correct. As you pointed out in the question, you then either need to constantly re-create them, create one global instance, or use static methods.
The OO paradigm would say that you should try to have a domain model where you map your database with entities. At least have an anemic domain model where entities are dull data container that are loaded/persisted in database. Then the OO paradigm would also say to put a bit of logic in the entities if possible.
It would also say to turn the services into objects to ease composition and reuse. If it was the case you could for instance wrap all services with an interceptor to start/stop transactions or do some security check, which you won't be able to do with static methods.
What you describe (no entities + stateless procedural services) is not considered a great OO design. I would suggest you introduce an anemic domain model at least and DAO. Regarding the sateless procedural services, this is actually the reality of many web applications -- if you don't need more you can stick to it.
My 2 cents
If you are mainly only using static classes then you've really taken out the object out of object oriented programming. I am not saying you are doing things incorrectly, I am saying maybe your system shouldn't lend itself to OOP. Maybe it is a simple app that requires some basic utility functions (sends email, etc). In this case most of your code becomes very procedural.
If you are dealing with databases you could have a static db class, and a simple business layer, and your php app interacts with your business layer which in turn interacts with your database layer. This becomes your typical 3-tier architecture (some people like to refer to this as 4 t-iers and seperate the actual database from the data layer, same thing).
If you are not really calling methods that require an object than what is the point of all of these static classes, just a question to ask yourself.
One thing you may notice is that if you plan on doing any kind of unit testing with mocking/stubbing you are probably going to have a hard time since static classes and methods are not easy to mock, stub or test.
I would be cautious about using static variables and classes in web applications. If you really must share an instance between users, then it should be ok to have a single instance (lookup "Singleton" design pattern).
However, if you trying to maintain state across pages, you should do this through either utilising the ViewState or by using the Session object.
If you were to have a global static variable, you could have a situation where concurrent users are fighting to update the same value.
Short answer: It's ok but you are foregoing the benefits of OOP.
One reasoning behind using objects is that most of the time there is more than one type of object that performs a role. For example you can swap your DBVendor1 data access object with a DBVendor2 data access object that has the same interface. This especially handy if you are using unit tests and need to swap objects that do real work with dummy objects (mocks and stubs). Think of your objects with the same interface as Lego bricks with different colors that fit together and are easily interchangeable. And you simply can't do that with static objects.
Of course, the increased flexibility of the objects comes at a price: The initialization of the objects and putting them together is more work (like you wrote) and leads to more code and objects that put together other objects. This is where creational design patterns like builder and factory come into play.
If you want to go that route, I advise you to read about dependency injection and using a DI framework.
Technically there is nothing wrong in doing it. But practically you are loosing lot of the benefits of object oriented programming. Also write the code/functionality where it belong to.. for example:
user.doSomeTask()
on the user object makes more sense than
UserUtils.doSomeTask(User user)
Using OOP concepts you abstract the functionality where it belongs to and in future it helps you change your code, extend the functionality more easily than using the static methods.
There are advantages to using static methods. One being that since you cannot inherit them they perform better. But using them all of the time limits you. The whole OOP paradigm
is based on re-usability of base classes thorough the use of inheritance.

Categories