How to access libraries inside a controller? - php

I'm building a small framework that I can use for repeated mundane stuff on future small projects.
I'm stuck on the best way to access libraries from inside a controller. I originally implemented a system similar to CodeIgniter's whereby my main controller class is basically a super object and loads all the classes into class variables which are then accessed by extending the controller and doing like $this->class->method()
I find that a little ugly, though. So I thought of just loading each class individually on a per-use basis in each controller method.
What's the best (cleanest) way of doing this?

To only ever have one instance of each class, you could create a simple service container.
class ServiceContainer
{
protected $services;
public function get($className)
{
if (!array_key_exists($className, $this->services)) {
$this->services[$className] = new $className;
}
return $this->services[$className]
}
}
Then create one ServiceContainer instance per application. Inject the container into all of your controllers and use
public function someAction()
{
$this->container->get('Mailer')->send($email_data);
}
Simple example, and obviously needs a lot of work to make useable (for instance autoloading needed and handling of file paths for ease of use, or easier way to add services without getting them, etc).

I dont like the way CodeIgniter does it. Its never seemed right to me. I favor an auto loading class pushed onto the spl_autoload stack. And then just calling the class as normal like:
$class = new SomeClass();

PHP provides autoload functionality with SPL and spl_autoload (and related functions). You can register a custom autoloader for your library code.
For the shared functionality handled by your application, have you considered the Front Controller design pattern?

Related

php - Dependency injection [duplicate]

I'm building a MVC PHP framework and I wonder which are the best practices to load what I need in my classes, be it other classes or plain configuration.
Till today I've used singletons, registry and lately a dependency injection container.
While many people claim that DI is the way to go, it seems to me like it justs moves the problem of coupling between components into another place.
Singletons introduce global state, registry introduces tight coupling and DI introduces... well, lots of complexity. I am still confused and can't find a proper way to wire my classes each other.
In the meanwhile, I came up with a custom solution. Actually it's not a solution, it just abstracts the implementation of service loading from my code.
I built an abstract class with _load_service and _load_config methods which all the components of my framework extend in order to load other services or configuration.
abstract class Base_Component {
function _load_service($service) {
// could be either
return DI_container::getInstance()->$service;
// or
$class = '\services\\'.$service;
return new $class;
// or other implementation
}
}
The implementation of loading them is now implemented in only one place, the base class, so at least I got rid of code lines like the following into my components:
$database = new Database(Registry::getInstance()->load('db_config'));
or
$database = DI_container::getInstance()->database;
Now if want a database instance I do this
$database = $this->_load_service('database');
and the implementation of service loader, container, registry or whatever can be easily changed in a single class method without having to search through all my code to change calls to whatever container implementation I was using before.
But as I said I'm not even close to sure about what method I will use for loading classes and configuration.
What are your opinions?
Why reinvent the wheel? Use Pimple as your DI container, and learn how to use it from its documentation.
Or, use Silex microframework as a base to create your own framework. It extends Pimple functionality, so you can use dependency injection.
To answer your question, this is how you use a DI without coupling your classes to it:
interface ContainerInterface {
public function getService($service_name);
public function registerService($service_name,Closure $service_definition);
}
class Application {
public function __construct(ContainerInterface $container) {
$this->container= $container;
}
public function run() {
// very simple to use!
$this->container->getService('db')->someDatabaseQuery();
}
}
$c = new My_DI_Container;
// Service definitions could be in a separate file
$c->registerService('db',function() { return new Database('some config'); });
// Then you inject your DI container into the objects that need it
$app = new Application($c);
$app->run(); // or whatever
This way, the DI container is decoupled and in the future you could use a different implementation. The only requirement is that it implements the ContainerInterface.
Note that the container object is being pushed, and not pulled. Avoid using singleton. To get/set single-instance objects, use the container (that's its responsibility). And to get the container instance, just push it through constructors.
Answer to your question; Look at PHP autoloading. Registering classes via autoloading makes it so you don't have to put require/includes everywhere, which really has a positive impact on RAD (rapid application development).
My thoughts:
Kudos for attempting such a daunting task, your approach appears to based on good practices such as singletons and factories.
I don't care for dependency injection. OOP is based on encapsulation, injecting one object into another, imo, breaks that encapsulation. When you inject an object into another object, the target object has to 'trust' that nothing regarding the injected object has changed, otherwise you may get unusual behavior.
Consider name-spacing your classes (not PHP name-spacing, but prefix your framework like Zend does, Zend_), this will help so you can register a namespace, then when a class is called the autoloader will ensure that the proper class is loaded. This is how Zend_Framework works. For specifics check out Zend_Loader_Autoloader. The Symfony framework actually takes this one step further; during the first request it will go through all known locations looking for class files, it will then build out an array of the classes and paths to the files then save the array to a file (file caching), so subsequent requests won't have the same overhead. Something to consider for your framework.
As far as config files go, Symfony uses YAML files, which I have found to be extremely flexible. You can even include PHP code for increased flexibility. Symfony has provided a stand-alone YAML parser that is easy to use. You can increase performance by adding a caching layer and caching parsed YAML files so you don't have to parse the files for every request.
I am assuming you are building your framework on top of an ORM. My recommendation would be not to any functionality specific to a version of the ORM, otherwise your framework becomes coupled with that version and you will have to upgrade both the ORM and the framework at the same time.
I would suggest looking under the hood at other frameworks and see if you can pick the best of each; resulting in a solid, easy to use framework.

Abstract, Interface and design patterns

I developed many years in PHP, using a small home-made MVC framework in PHP 5, never using PHP 5.2+ advantages.
I know what is a abstract class, and interface, and know the namespaces, and some design patters, but always struck in one simple thing, when is better use interfaces, abstract class or pattern design.
In my Framework I have a Core with Router class, the Router Calls the Core and the Core load the Controller and call the controller function using the Router vars.
The Controller extends the Core, and can use a function in the Core to load "components", this function is a simple singleton pattern, using a Static array, to instance the classes I "call" from the controller or other components, this is extremely fast and uses low memory, but is there a better way.
In the Controller or Component I write:
function example() {
$this->loadComponent(array('Cache', 'Template', 'Email'));
$this->Email->X();
}
This create the instances (if not exists, if exists return a pointer "&" tho the instance, not a copy) and set to the controller or component to allow using $this->ComponentName->XXXX
The function creates a copy, using $this->loadComponent(array('Cache' => 'Cache2')); if I need some copy and not the same. (for example for multiple DB connections)
I think this can be made better.
Now I am stuck in another design problem:
I have a Cache class, this class has 3 ways of cache, Memcache, Redis or File Cache.
The is a simple class (no abstract or interface), and cache functions are in separated class CacheMem, CacheRes, CacheFile, when the Cache class is loaded using loadComponent, the class reads a define config, and using this define do this:
function __construct() {
private $engine;
switch (CONFIG_CACHE_TYPE) {
case "MEM":
$class = 'CacheMem'
require ('Components'.DS.$class.'.php');
$this->engine = new CacheMem();
break;
case "RES":
$class = 'CacheRedis'
require ('Components'.DS.$class.'.php');
$this->engine = new CacheRedis();
break;
default:
$class = 'CacheFile';
require ('Components'.DS.$class.'.php');
$this->engine = new Cachefile();
break;
}
}
function read($key) {
$this->engine->read($key);
}
function write($key, $value, $time=3800) {
$this->engine->write($key, $value, $time=3800);
}
It there a better way to solve this? Its a simple simple problem, but I am stuck in one thing: I need to load the cache Class using the "Cache" name NOT CacheMem, CacheFile or CacheRes?
I tried using abstract class Cache, and extends with the Mem, Res or File, but I need to instance in the Cache class the children because I want to use "Cache" not "CacheXXX", and I know its wrong.
How do you recommend solve this?
there are many ways in oop to solve things bad :).
The Controler extends the Core, and can use a function in the Core
If you don't know whether to extend a class, ask yourself: is the controller a core? Hopefully it isn't. If your controller needs a core, then pass it in the constructor. The reason is 1. hide implementation, means 'injecting' the core and use is inside hides access to core over the controller, 2. only one extends is allowed, so use it carefully and smart, e.g. a car or bike is a vehicle, thus extending might be okay, if our vehicle has some implementation the car and bike use, but maybe Vehicle is just an interface without implementation.
This create the instances (if not exists, if exists return a pointer "&" tho the instance, not a copy)
PHP is using reference counted variables. Return a object means returning the reference. To copy an object, there is the clone operator in PHP.
switch (CONFIG_CACHE_TYPE)
What is CONFIG_CACHE_TYPE ? If it's a const defined before calling the construct, this is a bad idea. Just pass it as variable. And remember, that some switch cases like you use are violating the open-closed principle which is bad design.
switch(...) {
case ...:
... = new A();
case ...:
... = new B();
case ...:
... = new C();
...
}
In your special case I would create an interface CacheInterface and let your classes implement read and write, then just pass a CacheInterface to where you need caching.
As a rule of thumb: a good design does not need extends or abstract. oop beginners, but also some senior coders think, that oop is cool and reuse their code with extending lots of classes. Understanding extends and abstract does not mean you must use them whenever it's possible.
// edit: you've asked 2 questions and I've overlooked the first one. Check out DI (dependency injection) as creational pattern.

Where to load controller dependency classes?

I'm making my own primitive MVC framework with PHP, and I'm wondering where I should load/instantiate corresponding controller dependencies?
In the constructor of each controller (tightly coupled) or inject them (loosely coupled)?
The only part of the latter that I'm not too sure of is for the dependencies to be instantiated on bootstrap level, outside of the MVC paradigm, before being injected. Not every controller uses the exact same dependencies besides the default parent ones. I would have to instantiate them all, which would also create a lot of overhead.
I've seen some existing frameworks do it like $this->load->model('model'); // CodeIgniter in the constructor, but I have no clue on why they're doing it like that.
I would suggest you inject the dependencies, so your controllers are less coupled to your framework. This will make a switch to another framework easier.
About instantiating dependencies: I suggest you use (or implement) a dependency injection container. This container should contain factories that can instantiate services.
In an ideal situation your controllers are services too (meaning they too have factories in the dependency injection container).
This way only the controller you need for a particular request will be instantiated, and therefor only its dependencies are instantiated.
When building you own framework, this means that after the routing phase (when the correct controller is known), the framework should grab that controller from the container. The container itself will make sure all dependencies that are needed will be provided.
Have a look at Pimple for an example of a simple dependency injection container.
PS: That line from CodeIgniter looks a lot like the service locator pattern. This pattern is similar to dependency injection, but does not provide full inversion of control.
Q: Where should i load/instantiate corresponding controller dependencies?
There are multiple ways.
The load and instantiation concepts are basically "before/outside" and "after/inside".
Before and outside means, that you load the file containing a class (which you want to instantiate and pass to the controller), before you load the controller.
But how do you know, what the controller needs, before loading the controller? Uh..
Dependency Description Files
A description file comes into play, describing the wiring between your controller and it's dependencies. In other words, you can see the dependencies of your controller by looking at it's dependency description file. This concept is often used by Dependency Injection tools, which analyze the object and pull the dependencies names out automatically. It's also possible to maintain such a wiring configuration file manually. But it's tedious.
Service Locator
A Service Locator is a instantiation helper for dependencies.
Basically, it contains the same information like a dependency description file, but this time in form of a registry. The link between parts of your application becomes this registry.
Both strategies introduce overhead. It's a trade-off. When you change the perspective and look at things from an application with maybe 500+ classes, then you realize that a dependency injection tool is sometimes worth it.
Manual Injection
via Constructor Injection.
After and inside means, that you load the file containing your controller and then start to care about the dependencies.
At this point the class is not instantiated, yet, but the autoloader might do it's dirty deeds behind the scene. He evaluates the use statements at the top of your controller file. The use statements declare namespaced classes, which the autoloader resolves to actuall files and loads them. You might then start to use these classes as dependencies in your controller. This is probably the easiest way to solve your problem and i strongly suggest looking into the topics autoloading with namespaces and use-statements.
When the class is instantiated, you have the following possiblities:
use might use Setter Injection or Reference Injection to set the dependencies to the object. This requires that your Constructor Dependencies are already solved or your constructor is empty.
It's possible to combine these strategies.
Q: What does this do $this->load->model('model'); // CodeIgniter?
CodeIgniter is a legacy application framework. It was created in times, when namespaced autoloading wasn't available. $this->load is a basic class loading helper. This is the opposite of an "auto"loader, (which surprise, surprise) loads things automatically.
CodeIgniters loader class is used to load various other classes, like libraries or files from the view, helpers, models or user defined stuff. This is again the concept of a registry. Here the registry just knowns where things are in your application layout and resolves them. So $this->load->model('model'); means that the modelfunction must have some piecies of information, about the position of model files in your application.
You provide a model name and the path for the file is constructed by model.
And this is exaclty what it does (except a bit of overhead): https://github.com/EllisLab/CodeIgniter/blob/develop/system/core/Loader.php#L223.
Since I'm a Symfony developer, I can only give you a reference to Symfony.
I think you should do like they are doing in Symfony by thinking about what you need in each
Controller object.
At least, you need :
a Request object
and a Model loader object that gives you every Model you need.
Create a BaseController that implements these few functions and then extend it with custom Controllers.
You can also take a look on Silex : http://silex.sensiolabs.org/ a Micro Framework
Hope it helps.
When do you say "In the constructor" you mean to pass in the conatiner and pull the dependencies from them (in the constructor)?
<?php
class SomeController
{
public function __construct($container)
{
$this->service1 = $contanier->get('service1);
}
//...
}
I advice against that, though simpler and easier you will be coupling your controllers to the container thus using a ServiceLocator instead of truly inversion of control.
If you want your controllers to be easy unit-testable you should use inversion of control:
class SomeController
{
public function __construct($service1)
{
$this->service1 = $service1;
}
//...
}
And you can even create your controller as a service inside the container:
// this uses Pimple notation, I hope you get the point
$container['controller'] = function($c) {
return SomeController($c['service1']);
}
Use proxy services to lazy load them
Also if your controllers needs more than some services and you won't be using all of them you can:
1) Use proxy services in order to lazy load the service only when they are really needed
<?php
class ProxyService
{
/**
* #var Service1Type
*/
private $actualService;
public function __construct()
{
$this->actualService = null;
}
private function initialize()
{
$this->actualService = new Service1(); // This operation may take some time thus we deferred as long as possible
}
private function isInitialized()
{
return $this->actualService === null;
}
public function someActionOnThisService()
{
if (!$this->isInitalized()) {
$this->initalize();
}
$this->actualService->someActionOnThisService();
}
There you have a simple proxy object with lazy loading. You may want to check the fantastic Proxy Manager Library if you want to go that route
2) Split your controller
If your contoller has too many dependencies, you may want to split it.
In fact you may want to read the proposal by Paul M. Jones (lead developer of Aura Framework) about MVC-Refinement, IMHO is a good read even though you may not fully agree with it.
Even if you split your controller in order to reduce the dependencies, lazy loading your dependencies is a good idea (obviously you'll have to check weather if its doable in your context: more work in order to gain more speed).
Maybe you need to define __autoload() function before you try to load the Classes which is not loaded yet. Like:
function __autoload($className) {
require "/path/to/the/class/file/$className.php";
}
My example is very very simple to auto require the file which the class definition is in.
You can also use if-else statement or switch statement in that function to fit your own situations smartly.
The __autoload() function is called when PHP doesn't find the class definition, works for new, class_exists(), call_user_method(), etc, and absolutely for your dependences/parents classes. If there is still no class definition after __autoload() is called, PHP will generate an error.
Or you can use spl_autoload_register() function instead of __autoload() more gracefully.
For more information, you might want to see:
http://php.net/manual/en/function.autoload.php
http://php.net/manual/en/function.spl-autoload-register.php

Why does Codeigniter assume I want to create an instance of the class when using $this->load?

In Codeigniter, when we use $this->load('class_name') in the controller, CI will try to create an instance of the class/model using its constructor.
But sometimes, I don't actually need an instance from that class, I just want to call some static functions from it. Also, there is a big limitation with $this->load('class_name'), it does not allow me to pass parameters to the constructor (unless we extend or modify the core class of CI).
I think the $this->load('class_name') function should only do a require_once on the class php file for me, and let me freely do things (create instance/call static functions) with the class in the controller.
Should I simply ignore this function and use require_once or writing my own __autoload function to load up the classes? This way, I just feel strange because it seems I am not writing codes inside the CI box.
You can pass parameters to your constructor. See the "Passing Parameters When Initializing Your Class" section in the user guide.
I found CodeIgniter's object creation and loading to be very limiting. I want full control over my code, and little magic in the background. I have instead started using Doctrine's Class Loader. It's very lightweight and is essentially SPL autoloading (also a good alternative). You don't need the whole Doctrine shebang with ORM and all that stuff, just the ClassLoader. There's some configuration tinkering to get this right, but it works wonders.
With PHP 5.3 I now have namespaced classes in the Application directory. For instance I created a new class in the Tests directory: Application\Tests\SomeTest.php
That test could look something like this:
namespace Tests;
class SomeTest {
...
}
I would use this class in my code (controllers, views, helpers) by simply using the fully qualified namespace (i.e. $test = new \Tests\SomeTest) or a "use" statement at the top of my code (use \Tests\SomeTest as SomeTest).
In this way I intend to replace all libraries and models with OO namespaced variants. There are many benefits to this: fast autoloading with SPL, full IDE intellisense support for classes/methods (CodeIgniter is really bad for that), your code is more portable to other frameworks or projects.
That said, I still use a lot of the CodeIgniter engine. This basically means I have $CI =& get_instance() in most of my classes. It's still a work in progress and I think the main reason I need CI is for it's database access. If I can factor that out ... and use something like Dependency Injection, then I won't need CodeIgniter in my classes at all. I will simply be using it for it's MVC framework, and using it's methods occasionally in my controllers.
I know this goes above and beyond your question, but hopefully it's some food for though - and it helps me to get it in writing too.

How do I set up the following architecture

Sorry if the title is a little vague, I do not know how else to describe it.
I am making my own small framework. Things are going nicely and I am enjoying looking at topics that I usually do not need to check out as 'the magic' does it for me.
My framework is PHP based and I want it to run from a single instance. What I mean by this is the following.
class Controller_Name extends Controller {
public function __construct() {
$this->load->library('session');
$this->load->model('Model_Name');
}
}
class Model_Name extends Model {
public function something() {
if ($this->session->get($something))
// Do something Amazing
}
}
As hopefully illustrated above I want all controllers / Models / Views to share already loaded libraries.
So if a class is loaded in the Controller, I will be able to use it in a view file.
Does anyone know how this done? Can you point me in the direction of an article covering it, what this is called or some php function calls either completely or partly do the job.
As always, any answers are greatly appreciated.
If your aim is to make sure all dependencies inside your classes are resolved, have a look at the Service Containers from the Symfony Dependency Injection Component or the Stubbles framework.
Your controller can implement __get and intercept requests for libraries that have been loaded. Ideally you'd store the libraries in a static field to get the reuse you mentioned you wanted.
Also, to get load to behave like you want I'd personally create a Loader class and create an instance of it in the Controller. Then in the __get magic method I'd make it fetch it from the loader.

Categories