Codeigniter design patterns - php

Its been couple of years I have been working on Codeigniter and I just wanted to check design patterns. I wanted to implement different design patterns on my working projects so I could understand these stuffs in a better way.
I know Codeigniter is following MVC pattern, but which design pattern is codeigniter following ?
Can we say a database.php, a database class is implementing a singleton design pattern ? I am saying since as far as I percieved, on singleton, a single instance is created which provides a global access and that is what CI database config object does.

Yes, Codeigniter's loader currently follows the singleton pattern, or at least that's the pattern that most accurately describes it. When you execute the following:
$this->load->library('foo');
$this->load->model('foo');
$this->load->database('foo');
The loader does the following things:
Check to see if the class you're loading has been loaded previously by checking a registry of loaded classes. Silently ignore the request with a debug log entry if it has been loaded.
Instantiate the class with whatever parameters you set, create a reference to that object within the framework (singleton-ish) super object named after the class, or whatever custom name you pass. Store the reference, ignore subsequent attempts to load.
On bootstrap, the magic functions in the global scope behind the loader methods are used to construct the DB, core libraries, etc.
A more traditional singleton approach would do something like this (with auto loading):
return $className::instance();
... Where the instance method would return an instance, or construct if not yet instantiated, thus obviating any need to keep track of what has or has not been loaded. If the class has been loaded, a reference would be passed, otherwise a new object would be created and returned.
I suppose technically, CI is its own pattern in this regard, but close enough to a singleton that the term does accurately apply. It really is a singleton, just not implemented in a typical way.
At last I checked there were patches floating around for CI-3 that makes the loader much more flexible, allowing one to work outside of the super object as they please by returning an object or reference in these cases, but I don't know the status of Ellis Labs taking them.

Related

understanding Factory method pattern

I am reading factory method pattern as I have some issues related to it but I am unable to understand it from core. As per definition stated here
The creation of an object often requires complex processes not
appropriate to include within a composing object. The object's
creation may lead to a significant duplication of code, may require
information not accessible to the composing object, may not provide a
sufficient level of abstraction, or may otherwise not be part of the
composing object's concerns.
I can understand the concept of duplication of significant code, but I am unable to understand the other concepts like it states
It may require information not accessible to the composing object
How a class can contain the infomation which ic not accessible by composing object. As for as I understand it may be any private datamember of the class. But if any thing is private then how object creation process needs that information? Similarly other two point
It may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns.
Can any body please here describe these precisely and show my some code stuff so that I can understand the concept
The idea of factory pattern is to create load classes and create new objects dynamically. Quite often it is done as a static class (such as here, in the official PHP documentation), but some frameworks use factory pattern as a way of loading objects within MVC objects, for example when you want to load some data in view through a model.
The idea of factory pattern is efficiency and resource management. It loads a file only when it's not been loaded yet and returns the newly created object.
(Note that the example in PHP documentation is not ideal, it would be better to check if the class has been defined and if not, then attempt to include the file instead of using include_once())
when it comes to use an external resource in our object there alternatives for its creation come to mind :
To create the object using its constructor
To ask another object to create it for our object (Factory and
Factory method pattern) .This way our object doesn't know how to
create the external resource but it should know who to ask for
it.(it needs to hold a reference to the factory or knows the type of
the factory in case of calling a static factory method)
To inject the external resource using an IoC (inversion of control)
container.This way our object doesn't to know nothing about neither
how to create the external resource nor who is responsible for its
creation.Actually this method is making factory patterns obsolete.
Imagine you are writing an API through which users can create and use a certain object. Internally, in the API framework, you want to register your object in some services, listeners, database...
Here you have two different ways of dealing with the situation:
You either let the user create the object and take the responsibility of registering it in the services, listeners and database which should be exposed (public).
OR
You want to provide a public factory class that will create the object given certain parameters and will take care of doing all the necessary initialization for you.
The second scenario is the best way to hide all the complexity of creating such objects in your system. This also has a big benefit of hiding the services, listeners and databases needed to register the created object.

Why use Zend_Registry instead of the Singelton pattern?

Why should I use Zend_Registry instead of the Singleton pattern?
My coworker and me recently had a discussion about this. His point was that we should use Zend_Registry for all consistent objects, but I wanted to use the singleton pattern, since Zend_Registry just does the same, but wrapped.
I have a problem with code like this:
$list = Zend_Registry::get('database')->getList($sql);
Since theres a chance that database isn't in Zend_Registry. In cases of lazy loading, I would have to make my own registry with information about specific objects in my system. Like if the database takes specific parameters on loadtime, then it would have to know this.
I would instead use getInstance and then all the code would reside in the same object. Does that make sense?
Even though you phrased your question as an either/or, might I suggest a third alternative?
I try to avoid both singletons and Zend_Registry wherever possible, since they function, in effect, as globals. When a segment of code can reach into the global ether - via a call to a singleton or a global registry - to get something it needs, it creates a hidden - or at least, a non-explicit - dependency that makes things harder to debug and unit-test.
In contrast, I try to follow dependency injection advice, paraphrased as: "Give a component what it needs. Don't make it find what it needs."
I find that for most entities for which I might feel I need a registry/singleton - db connections, loggers, etc - I can create them at Bootstrap, store them in the Bootstrap registry and inject them into my controllers, usually during init() using $this->getInvokeArg('bootstrap')->getResource('myResource'). Only controllers reach back into the Bootstrap. Then, any models or services that need these dependencies get them passed-in explicitly by the controller, either via constructor or by setter injection.
A hybrid approach to which I do sometimes fall back is to design my service/model classes with getters/setters for these dependencies - getDbAdapter() and setDbAdapter(); getLogger() and setLogger(), etc. The getter lazy-loads from the global registry - whether some singleton or by Zend_Registry, throwing exceptions when they are not where I expect them to be. In that sense, it is similar to what you are suggesting. It does violate the purist dependency injection philosophy. But at least the presence of the getter/setter methods explicitly demonstrates that there is a dependency and allows me to mock it out or to provide non-default implementations.
It does for simple blog or something. Otherwise you're stuck with only one DB instance. And that's NOT what you want in the long run. You may want to connect to other server (to log errors to central db, to import products from someone, ...) or connect as different user (for security reasons - you don't want your API to have access to admin_users table, but you still need to connect to it to check if user is valid in the first place).
You can do one-purpose registers (My_Db_Admin, My_Db_ReadOnly, ...) but that does not make much sense to me. Using registry you're not stuck with one instance. You can create one outside registry and work with it for a while and then trash it ;)

Confused About Objects and Classes in CodeIgniter?

I’m fairly new to CodeIgniter and have a question. I’m a bit confused about Classes, Libraries and Objects.
Does CodeIgniter replace the normal PHP way of usings objects i.e. $var = new car(); with libraries i.e. $this->load->library('some_library'); $this->some_library->some_function(); ?
If both are valid, is there a difference? If so, what are the differences and when do I use one over the other? Which is more common/proper?
I am asking because I created a class, but I'm not certain what is the correct manner in which to instantiate it.
Thanks in advance
I am not familiar with CodeIgnitier. But familiar with other PHP frameworks. Most of frameworks use this way for performance improvements, registering things, executing certain events, and making things simpler for developer...
For example if you want to create class "car" with is somewhere in library directory you would have to include the file first before you can create object of that class (miltiple lines of code, more room for error). The framework will create the class and includes related files in 1 line of code (easier and safer).
Framework way also works as a factory. Instead of recreating an object, it will create object only once and every time you call the method again it will return the reference to existing object.
More things are happening behind the scenes when you use framework. Things are getting registered, etc...
CI doesn't replace class behavior per se, it simply adds functionality that allows access to custom libraries/models/views as singleton objects via the core object for simplicity.
Nothing is stopping you from creating (as I have in one of my projects) additional files with classes for non-singleton entities and require them in a model for further use. On hindsight, I should probably have used helpers for this.
What the loader ($this->load) class does, among other things, is it creates a single object of the specified class (model, library or view - not helpers though, see below) and attaches it as a property of the core class that is normally accessible via $this.
Helpers are a bit different. They are not attached, but instead simply 'read' into the global namespace from the point where they are loaded.
To answer your question, it would be more proper to use the loader class in instances where you don't need more than one instance of a class created. If you need 'entity' classes, your best CI-compliant bet would be to create them as helpers.
Given only this context, this looks like Inversion of Control (maybe I'm wrong, I haven't looked too closely at CodeIgniter).
You don't want to rely on the type car as in new car(). What if later you want to make $var a racecar? $var can still do the same things, but it is forced to be a car because you constructed it directly. Or what if you are testing this class, but car is some complex object which calls some external service. You want to test your logic, but don't care if the car service isn't working. So you should be able to change $var to actually load a mockcar. You can't do that if you do $var = new car().
What is Inversion of Control?

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.

OOPHP suitable alternative to singleton pattern?

I'm currently working on an oophp application. I have a site class which will contain all of the configuration settings for the app. Originally, I was going to use the singleton pattern to allow each object to reference a single instance of the site object, however mainly due to testing issues involved in this pattern, I've decided to try a different approach.
I would like to make the site class the main parent class in my app and call it's constructor from within the constructors of the child classes, in order to make all the properties available whenever needed.
When run for the first time, the class will only contain the db details for the app. To get the remaining values a query must be performed using the db details.  However, any subsequent instances will be clones of the original (with all values). I may also set a Boolean flag to perform the query again a completely new instance is required.
Would this be a viable alternative to the singleton and would it solve the testing issues it causes? This is all theory atm, I haven't started to code anything yet,
Any thoughts or advice greatly appreciated.
Thanks.
I think a better way is to have an 'configuration' object that will get passed to the constructors of all your other classes. So, almost something like a singleton, except it's explicitly created and passed only to classes that need it. This approach is usually called dependency injection.
After trying many different techniques, what I have found functional and reliable is this method:
Use a bootstrap, or initialization file. It is located in the ROOT of the site with the proper permission and safe-guards against direct access.
All pages in the site first include this file. Within it, I create all my global objects (settings, user), and reference them from there.
For example:
// OBJECT CREATION
$Config = new Configuration();
$User = new User();
Then within classes that require these objects:
public function __construct($id = NULL) {
global $Config; // DEPENDENCY INJECTION SOUNDS LIKE AN ADDICTION!
if($Config->allow_something) {
$this->can_do_something = true;
}
if(NULL !== $id) {
$this->load_record($id);
}
}
Notice that I just access these global objects from within the class, and how I don't have to include the object variables as the first constructor parameter each and every time. That gets old.
Also, having a static Database class has been very helpful. There are no objects I have to worry about passing, I can just call $row = DB::select_row($sql_statement);; check out the PhpConsole class.
UPDATE
Thanks for the upvote, whoever did that. It has called attention to the fact that my answer is not something I am proud of. While it might help the OP accomplish what they wanted, it is NOT a good practice.
Passing objects to new object constructors is a good practice (dependency injection), and while "inconvenient," as with other things in life, the extra effort is worth it.
The only redeeming part of my answer is use of the facade pattern (eg. DB::select_row()). This is not necessarily a singleton (something the OP wanted to avoid), and gives you an opportunity to present a slimmed down interface.
Laravel is a modern PHP framework that uses dependency injection and facades, among other proven design patterns. I suggest that any novice developer review these and other such design practices thoroughly.

Categories