Puzzled with Dependency Injection in PHP (chains of Classes) - php

I'm moving from Globals and Singletons (=bad?) to Dependency Injections (=good?) in PHP and I'm very new to it.
I have read many related topics on Stack Overflow already but I still can't understand the main principles of DI.
Please tell me if I'm doing it right (it's just shortened pseudo-code):
// first connect to DB
$sql = new Sql();
// create logger (I'm writing logs to Database so I need to pass $sql to it)
$log = new Log($sql);
// restore logged in user, get info about user, unread messages...
// class "User" needs access to Database and Logs:
$user = new User($sql, $log);
// now we need to collect all the data of current section of my Website
// I'm using Model and Controller:
$model = new FrontPageModel($sql, $user, $log);
$pageController = new FrontPageController($model);
Though it may look OK at this step but what if I need to get access to more classes like Config, Session, etc.?
Should my code transform to this?
$model = new FrontPageModel($sql, $user, $log, $config, $session);
Isn't it too much already?
I know someone could advice to use a kind of big "Application" class and put Config, Session, Log, Db objects inside of this class but I feel that it isn't very good idea.
Next question - what if I need to get logged User's ID inside of my FrontPageController? I did not pass an instance of "User" to FrontPageController, but it was passed before (in chain) to FronPageModel.
class FrontPageController{
private $model;
function __construct($model){
$this->model = $model;
}
function getData(){
echo $this->model->user->id; // is it right way?
}
}
That "$this->model->user->id" seems like overkill to me.

It might not be the prettiest, but you're certainly not doing it "wrong". You're demonstrating classing constructor injection, but you could perhaps refactor to keep some of the disparate objects separated a bit more.
My suggestion would be to look at established PHP DI containers. See how they work, use them in a few apps, and (1) you'll have much more testable apps and (2) you'll be much more comfortable with DI in general.
Take a look at one or more of the following:
Pimple
Aura DI
Symfony DI

Like all the joyful stuff, it' depends.
I would put everything inside a factory class, or several factory classes for different sub systems.
class AppFactory {
protected $_sql;
public function getSql()
{
if (!empty($this->_sql))
return $this->_sql;
$this->_sql = new Sql();
}
}
Then initial it on application run. Configure if needed.
$factory = new AppFactory();
// set config
// $factory->internallyGenerateSingletons = true;
And now every other class can use it. And of course you have injection to put factory inside.
$model = new FrontPageModel($factory);
// or
// $model->useFactory($factory);
Regarding other question. Is this the right way.
...
$this->model->user->id
...
I would say it's ok but batter is to use methods like this:
...
$this->model->getUser()->id
..
So you can mock user class when doing unit testing. And it makes application more flexible.

It seems like you have got the idea of dependency injection right. You even question Symfonies idea of DI (in a comment), which shows more mature understanding.
A next step to solving the questions you have is to take a step away from leaking technical information from one layer into another. Eg your controllers don't care that they talk to a model. Your model doesn't care it talks to an sql or nosql database.
Another is about responsabilities. Does the user really need to do all of that? Is the user responsible for logging? It may be a correct choice, but it also seems that you ask it to do a lot of things. Does the user construct itself, update itself? etc
$this->model->user->id; // is it right way? Is not the right way. 1) This is very strong coupling. 2) do you need the id of the user? is the user only put in as dependency to get something from it? perhaps something like $this->user->showUserInfo($userInfoDisplay) can be used?

Related

OOP object models, best practice [duplicate]

I'm not new to PHP or programming at all. But recently I was thinking about website programming in PHP and how easier it was before the OOP. Anyway, I prefer OOP than the old procedural style.
I want to implement a website but it seems I always have to use a global or a static variables. And I'm starting to wonder, how can I do it without those?
Anyway, what I'm talking about is having a class for each "component" of the website.
For example if it was an url shortener website it would be: links, members, database.
What I'm talking about is way more complicated, at least 8 classes.
Anyway, my current approach is the following:
$database = new Database(...);
$links = new Links($db);
$users = new Users($db);
Anyway, for example I want to get all the links a user posted by its ID, I need to use both links and both users components.
Is there any other way I could do this? Any other approach? except passing them as constructor parameters.
You should have the following components:
Business objects, which model and express one particular "thing" in your app:
class Link { ... }
class User { ... }
These don't "do" anything, they're just there to formalise your data structures. These objects have getter and setter methods to get and set individual attributes, which are also validated there:
public function setUrl($url) {
if (!/* validate the URL here*/) {
throw new InvalidArgumentException("$url is not a valid URL");
}
$this->url = $url;
}
Minimum required data is part of the constructor. This ensures your data integrity application-wide. It allows you to assert that when you have an instance of Link, the data expressed by it is minimum valid data for a link.
A database link. Only the bare necessary thing to connect to a database, nothing more, nothing less. A raw PDO or mysqli object will do just fine.
A data-object mapper, which takes a database link and knows how to store business objects in the database and how to retrieve them:
class LinkStorage {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
}
This class has all the various methods of how to retrieve things from your database:
public function getById($id) {
$stmt = $this->db->prepare('SELECT ... FROM ... WHERE id = :id');
$stmt->execute(compact('id'));
if (!$data = $stmt->fetch()) {
throw new RuntimeException("Record with id $id does not exist");
}
return new Link($data['url']);
}
You can have all sorts of different queries encapsulated this way, e.g.:
/**
* Returns all links by a particular user.
* #param User $user
* #return Link[]
*/
public function getAllFromUser(User $user) {
...
}
The usage is then simple:
$db = new PDO(...);
$linkStorage = new LinkStorage($db);
$userStorage = new UserStorage($db);
$user = $userStorage->getById($id);
$links = $linkStorage->getAllFromUser($user);
This kind of code would then be encapsulated in a service class, which holds all the possible "actions" you can do in your app. registerUser(array $data), getLinksOfUser($id), newLinkFromPostData(array $data) etc.
What I've just described is basically the model portion of an MVC-style application. The other two parts would be controllers which call the service methods, and views which output data retrieved from service methods. This approach keeps responsibilities separate and isolated and allows you to put higher-level logic and functionality together like building blocks. Business objects are the lowest building block, their structure needs to be solid and well defined for the rest to work. Data-object mappers just concern themselves with putting those objects into the database and getting them back out again. Services then put all this together in various complex ways and make things happen.
You shouldn't have any cyclic dependencies with this, as responsibilities are well separated. Your individual dependencies may still be somewhat complex. If it becomes too cumbersome to instantiate classes, you'll want to look into Factories:
$factory = new Factory;
$userStorage = $factory->newUserStorage();
All the complexity of instantiation is encapsulated in this factory. One step further are dependency injection containers, who you can configure in, for example, an XML file to specify which class depends on what, and then the DI container will take care of it for you.
I was thinking about website programming in PHP and how easier it was
before the OOP
Well, stick to procedural then. If it is easier to write a well written website in a procedural or functional way then opposed to the ojbect-oriented way. Stick ti what you are used to. OO isn't better then functional. It's just a different approach.
the public void main() in php
In the lanuage Java every piece of software we write has a single entry point. The public void main() method. This method fires up the entire application and passes in the arguments provided on startup. It is also the only exit point in the application. the application ends in this method (unless it crashes).
In php, there is no single entry point. We have a bunch of files that run some scripts that do some more stuff and then somewhere along the line another script decides to return stuff and die();
Dependency injection and how IoC libraries can help
When using dependency injection, it becomes a real pain in the a$$ when creating objects and passing arround the correct instance of a class. We start solving this problem with ugly solutions: Singleton, globals, statics, ... Making our software more and more tightly coupled and harder to maintain.
Inversion of Control can help here. there are some really greate articles on the webz.
You can use autoloading in PHP for a better solution:
http://php.net/manual/en/language.oop5.autoload.php

Looking for a way to handle/approach PHP OOP websites

I'm not new to PHP or programming at all. But recently I was thinking about website programming in PHP and how easier it was before the OOP. Anyway, I prefer OOP than the old procedural style.
I want to implement a website but it seems I always have to use a global or a static variables. And I'm starting to wonder, how can I do it without those?
Anyway, what I'm talking about is having a class for each "component" of the website.
For example if it was an url shortener website it would be: links, members, database.
What I'm talking about is way more complicated, at least 8 classes.
Anyway, my current approach is the following:
$database = new Database(...);
$links = new Links($db);
$users = new Users($db);
Anyway, for example I want to get all the links a user posted by its ID, I need to use both links and both users components.
Is there any other way I could do this? Any other approach? except passing them as constructor parameters.
You should have the following components:
Business objects, which model and express one particular "thing" in your app:
class Link { ... }
class User { ... }
These don't "do" anything, they're just there to formalise your data structures. These objects have getter and setter methods to get and set individual attributes, which are also validated there:
public function setUrl($url) {
if (!/* validate the URL here*/) {
throw new InvalidArgumentException("$url is not a valid URL");
}
$this->url = $url;
}
Minimum required data is part of the constructor. This ensures your data integrity application-wide. It allows you to assert that when you have an instance of Link, the data expressed by it is minimum valid data for a link.
A database link. Only the bare necessary thing to connect to a database, nothing more, nothing less. A raw PDO or mysqli object will do just fine.
A data-object mapper, which takes a database link and knows how to store business objects in the database and how to retrieve them:
class LinkStorage {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
}
This class has all the various methods of how to retrieve things from your database:
public function getById($id) {
$stmt = $this->db->prepare('SELECT ... FROM ... WHERE id = :id');
$stmt->execute(compact('id'));
if (!$data = $stmt->fetch()) {
throw new RuntimeException("Record with id $id does not exist");
}
return new Link($data['url']);
}
You can have all sorts of different queries encapsulated this way, e.g.:
/**
* Returns all links by a particular user.
* #param User $user
* #return Link[]
*/
public function getAllFromUser(User $user) {
...
}
The usage is then simple:
$db = new PDO(...);
$linkStorage = new LinkStorage($db);
$userStorage = new UserStorage($db);
$user = $userStorage->getById($id);
$links = $linkStorage->getAllFromUser($user);
This kind of code would then be encapsulated in a service class, which holds all the possible "actions" you can do in your app. registerUser(array $data), getLinksOfUser($id), newLinkFromPostData(array $data) etc.
What I've just described is basically the model portion of an MVC-style application. The other two parts would be controllers which call the service methods, and views which output data retrieved from service methods. This approach keeps responsibilities separate and isolated and allows you to put higher-level logic and functionality together like building blocks. Business objects are the lowest building block, their structure needs to be solid and well defined for the rest to work. Data-object mappers just concern themselves with putting those objects into the database and getting them back out again. Services then put all this together in various complex ways and make things happen.
You shouldn't have any cyclic dependencies with this, as responsibilities are well separated. Your individual dependencies may still be somewhat complex. If it becomes too cumbersome to instantiate classes, you'll want to look into Factories:
$factory = new Factory;
$userStorage = $factory->newUserStorage();
All the complexity of instantiation is encapsulated in this factory. One step further are dependency injection containers, who you can configure in, for example, an XML file to specify which class depends on what, and then the DI container will take care of it for you.
I was thinking about website programming in PHP and how easier it was
before the OOP
Well, stick to procedural then. If it is easier to write a well written website in a procedural or functional way then opposed to the ojbect-oriented way. Stick ti what you are used to. OO isn't better then functional. It's just a different approach.
the public void main() in php
In the lanuage Java every piece of software we write has a single entry point. The public void main() method. This method fires up the entire application and passes in the arguments provided on startup. It is also the only exit point in the application. the application ends in this method (unless it crashes).
In php, there is no single entry point. We have a bunch of files that run some scripts that do some more stuff and then somewhere along the line another script decides to return stuff and die();
Dependency injection and how IoC libraries can help
When using dependency injection, it becomes a real pain in the a$$ when creating objects and passing arround the correct instance of a class. We start solving this problem with ugly solutions: Singleton, globals, statics, ... Making our software more and more tightly coupled and harder to maintain.
Inversion of Control can help here. there are some really greate articles on the webz.
You can use autoloading in PHP for a better solution:
http://php.net/manual/en/language.oop5.autoload.php

How to build a PHP Dependency Injection Container

I've recently learned about the advantages of using Dependency Injection (DI) in my PHP application. However, I'm still unsure how to create my container for the dependencies, or whether I should be using DI at all for the online forum that I'm building.
The following code is my version of the DI container I have made based on the example I learned from here .
class ioc {
var $db;
var $session;
var $user_id;
static function newUser(static::$db, static::$user_id) {
$user = new User($db, $user_id);
return $user;
}
static function newLogin(static::$db, static::$session) {
$login = new Login($db, $session);
return $login;
}
}
$user = ioc::newUser();
$login = ioc::newLogin();
I have a few questions:
1) Where should I instantiate my injected dependencies, such as $database, $session, etc? Would it be outside the container class, or inside the container's constructor.
2) What if I need to create a multiple instances of the User class inside other classes? I can't inject the previously instantiated $user object because that instance is already being used. However, creating the multiple User instances inside of another class would violate the rules of DI. For example:
class Users {
function __construct($db, $user_id) {
$this->db = $db;
$this->user_id = $user_id;
}
function create_friends_list() {
$st = $this->$db->prepare("SELECT user_id FROM friends WHERE user_id = $this->user_id");
$st->execute();
while($row = $st->fetch()) {
$friend = ioc::newUser($row['user_id']);
$friend->get_user_name();
$friend->get_profile_picture();
}
}
}
3) I'm wondering if I should even adopt DI, knowing that I have to rewrite all of my previous code. I've previously been relying on global variables that I instantiate in my initialize.php, which is included in all my files.
It seems to me that DI creates a lot of overhead and there are situations where it is unusable (as in my #2 example). The following site is from a developer who cites many good reasons not to use DI. Does his arguments have any merit? Or am I just using DI wrong?
check this link.
Where should I instantiate my injected dependencies, such as $database, $session, etc? Would it be outside the container class, or inside the container's constructor.
Ideally your database connection and session would be bootstrapped in. Proper DI requires an instance of a base object for which everything is registered into. So taking your IOC class as an example you need to make an instance of it ($ioc = new IOC();) then you need some kind of service provider class say
$ioc->register('database', new DatabaseServiceProvider($host, $user, $pass))
Now every time you want a connection to the database you just need to pass in $ioc->get('database'); a very rough example but I think you can see the idea is basically to store everything inside a registry and nothing is statically binded meaning you can create another instance of $ioc with totally different settings making it easy to create connections to say a different database for testing purposes.
What if I need to create a multiple instances of the User class inside other classes? I can't inject the previously instantiated $user object because that instance is already being used. However, creating the multiple User instances inside of another class would violate the rules of DI.
This is a common issue and there are multiple different solutions. Firstly your DI should show the difference between logged in user and just a user. You would probably want to register your logged in user but not just any user. make your user class just normal and use
$ioc->register('login-user', User::fetch($ioc->get('database'), $user_id));
so now $ioc->get('login-user') returns your logged in user. You can then use User->fetchAll($ioc->get('database')); to get all your users.
I'm wondering if I should even adopt DI, knowing that I have to rewrite all of my previous code. I've previously been relying on global variables that I instantiate in my initialize.php, which is included in all my files.
If you need to rewrite all your code to use DI you shouldn't probably do it. Maybe look into making a new project and work in some of your old code if you have the time. If your codebase is large I would recommend looking into breaking it down into smaller projects and using RESTFUL apis for getting and saving data. Good examples of writing APIs would be for putting your forum search into its own application /search/name?partial-name=bob would return all users with the word bob in it. you could build it up and make it better over time and use it in your main forum
I hope you understand my answers but if you need any more info let me know.
I was going to write this a comment, but it grew too long. I am not an expert so I will just give my point of view from what I've learned through few years practicing and here in SO. Feel free to use or question any part of my answer (or none).
1.- Outside. What does the container do? The answer should be a single thing. It shouldn't have to be responsible to initialize the classes, connect to the database, handle the session and other things. Each class does one thing only.
class ioc
{
public $db;
// Only pass here the things that the class REALLY needs
static public function set($var, $val)
{
return $this->$var = $val;
}
static function newDB($user, $pass)
{
return new PDO('mysql:host=localhost;dbname=test', $user, $pass);
}
static function newUser($user_id)
{
return new User($db, $user_id);
}
static function newLogin($session)
{
return new Login($this->db, $session);
}
}
if (ioc::set('db',ioc::newDB($user, $pass)))
{
$user = ioc::newUser($user_id);
$login = ioc::newLogin($session);
}
2.- You shouldn't do $friend = ioc::newUser($row['user_id']); inside your class. There you are assuming that there's a class called ioc with a method called newUser(), while each class should be able to act on it's own, not based on [possibly] other existing classes. This is called tight coupling. Basically, that's why you shouldn't use global variables either. Anything used within a class should be passed to it, not assumed in the global scope. Even if you know it's there and your code works, it makes the class not reusable for other projects and much harder to test. I will not extend myself (PUN?) but put a great video I discovered here in SO so you can dig more: The Clean Code Talks - Don't Look For Things.
I'm not sure about how the class User behaves, but this is how I'd do it (not necessary right):
// Allow me to change the name to Friends to avoid confusions
class Friends
{
function __construct($db)
{
$this->db = $db;
}
function create_friends_list($user_id)
{
if (!empty(id))
{
// Protect it from injection if your $user_id MIGHT come from a $_POST or whatever
$st = $this->$db->prepare("SELECT user_id FROM friends WHERE user_id = ?");
$st->execute(array($user_id));
$AllData = $st->fetchAll()
return $AllData;
}
else return null;
}
// Pass the $friend object
function get_friend_data($friend)
{
$FriendData = array ('Name' => $friend->get_user_name(), 'Picture' => $friend->get_profile_picture());
return $FriendData;
}
}
$User = ioc::newUser($user_id);
$Friends = new Friends($db);
$AllFriendsIDs = array();
if ($AllFriendsIDs = $Friends->create_friends_list($User->get('user_id')))
foreach ($AllFriendsIDs as $Friend)
{
// OPTION 1. Return the name, id and whatever in an array for the user object passed.
$FriendData = $Friends->get_friend_data(ioc::newUser($Friend['user_id']));
// Do anything you want with $FriendData
// OPTION 2. Ditch the get_friend_data and work with it here directly. You're already in a loop.
// Create the object (User) Friend.
$Friend = ioc::newUser($Friend['user_id']);
$Friend->get_user_name();
$Friend->get_profile_picture();
}
I didn't test it, so it has probably some small bugs.
3.- If you are learning while coding, you will have to rewrite MANY things. Try to do somethings right from the beginning so you don't need to rewrite everything, but only the classes/methods and adopting some conventions for all your code. For example, never echo from within the function/method, always return and echo from outside. I'd say that yes, it's worth it. It's bad that you have to loose 1 or 2 hours just rewriting something, but if it has to be done, do it.
PS, sorry, I changed your bracket style everywhere.
EDIT
Reading other answers, while you shouldn't connect to the database with your ioc object, it should be perfeclty fine create a new object with it. Edited above to see what I mean.
Instead of globals in your init.php define your objects like:
ioc::register('user', function() {
return new User();
});
And inisde your create_friends_list method use:
ioc::get('user')->newUser($user_id);
This is a really plain implementation. Check out:
http://net.tutsplus.com/tutorials/php/dependency-injection-huh/?search_index=2
or
http://net.tutsplus.com/tutorials/php/dependency-injection-in-php/?search_index=1
for more information.
The question you asked has one very important catch, which I asked about in a comment. Any time you examine the possibility of pausing forward progress in order to go back and accomplish a less than trivial re-factoring of existing classes, you have to really think about the payoff.
You replied:
It seems a bit complex (and very different) and more work than it's worth to implement at this point. I'm just trying to hack out something real quick and see if it gains traction.
Remember that you have the following things to do if you want to implement an DI with an IoC container properly:
Implement the IoC container and registry at bootstrap
Modify all existing classes that have dependencies to allow setter injection, while not depending on the IoC container itself
Re-writing / Re-structuring of your tests as needed
A note on the second bullet which reflects my own personal view and preference, developing with DI in mind can be hard and you want the full reward it can give. One of the biggest rewards is completely decoupled objects, you don't get the complete part of that if everything still depends on an IoC container.
That's a lot of work, especially if you haven't been considering the pattern until now. Sure, you'll have clear benefits, such as lots of re-usable and easily testable objects when you're done. But, as with all re-factoring, nothing new would be accomplished in the context of adding or finishing new functionality and features. Is difficulty testing or tight coupling getting in the way of that? That's something you'd have to weigh.
What I suggest you do instead is keep the pattern in mind as you write new code. Provide setter methods to inject dependencies, which can be utilized manually or through an IoC container. However, have your classes continue to create them just in time if none have been injected and avoid composition in a constructor.
At that point you'll have a collection of classes that lend much better to inversion of control, if that's a pattern you want to pursue in the future. If it works well for you and it's something you really want to incorporate into your design decisions, you can easily re-factor to remove the JIT logic later.
In conclusion, I'm afraid that the only thing you'll end up with if you try implementing it completely, and properly right now is a mess. You can change how you write classes now going forward, but I wouldn't go back and try to implement it across the board.

Should I be using dependency injection in my php project?

I've recently learned the merits of dependency injection but am wondering if I should be using it in my project since I don't even require a full blown mvc. Now that I'm using it I'm realizing the extra overhead in each page that I write. For example...
require_once '../../include/session.class.php';
require_once '../../include/db.class.php';
require_once '../../include/account.class.php';
$objSession = new Session();
$objDb = new Db();
$objAccount = new Account( $objSession, $objDb );
account.class.php
class Account {
...
public function __construct( Session $objSession, Db $objDb ) {
$this->session = $objSession;
$this->db = $objDb;
}
}
...the Account class will always need Db and Session and I'll only ever have one class of each. So my question is, should I be using DI in a situation like this or should I just use...
account.class.php
require_once '../../include/session.class.php';
require_once '../../include/db.class.php';
class Account {
...
public function __construct() {
$this->session = new Session();
$this->db = new Db();
}
}
...?
Dependency Injection has nothing to do with MVC. It is really good at making unit tests easier to write and ultimately I have found that it makes me really think about the resources that I'm using and whether or not that implementation should be using that resource.
I personally don't see the harm in creating the injected object, so you've got a couple lines where you have to create an object? It tells the user a lot more about what's going on. I'd rather have clarity as compared to magic.
Personally, I think most of the clutter in the code is coming from the require statements. I'd say an autoloader would solve some of that problem.
I really enjoyed this Google Clean Code Talk on DI. It helped me grasp the concept and its benefits a little better.
You've read about the merits of dependency injection. Why did you start using it?
Was it because of the ability to swap out those particular dependencies for testing or different environments? Was it to isolate and make explicit the order of a circular chain of dependencies?
Suppose, for example, that it was the desire to inject different classes for testing purposes (the merit of DI that made me use it). How do you handle that without DI?
Look at your Account class. You can either modify the constructor with an if check on some predicate testMode(), or you can modify the Db and Session constructors, or you could possibly change a configuration file. Whatever non DI solution you opt for, are you ok with that? What about other dependencies (emailer, logger, etc)? Do you have any interfaces to external systems that you should mock for testing?
Anyway, the answer could be that you are satisfied without the DI solution and that your app is small enough to manage without it. But it's important to ask yourself the question anyway.
Similarly, apply that same line of questioning to the other merits of DI that motivated you to start using it.
Incidentally, do you have one instance of Db in Account and another in each of your other classes? Could you have just one instance? DI helps with that. You can have singleton classes without actually coding them as singletons by always injecting the same instance.
Out of curiosity, why are you doing your own dependency injection instead of using a DI library? Half of the benefit of using DI is that it is cleanly abstracted away by other people's implementations. Only write the code you need to and let the libraries take care of doing the injection for you. This is similar to drrcknlsn's suggestion, but without writing the actual implementation of the DependencyInjectionContainer class:
$account = DependencyInjectionContainer::build('Account');
and screw the rest.
A good DI library should see the constructor for Account, realize it needs a Db and a Session, and march up the chain of constructors (in this case, it ends there since both have empty constructors). That translates to having the same amount of code as the non DI case (plus the arguments to the constructor, minus the calls to the constructors inside, but no extra crap at top), with whatever benefits brought you to DI in the first place.
Dependency injection containers were invented to solve this very problem. Consider:
$account = DependencyInjectionContainer::build('Account');
The DependencyInjectionContainer class would handle the injection:
public static function build($class) {
switch ($class) {
case 'Account':
$session = new Session();
$db = new Db();
return new Account($session, $db);
// ...
}
}

Dependency-injection in real life

I am building a really minimal MVC framework to increase my PHP knowledge and challenge myself. I've come to the point where Classes begin to be dependent on each other to work.
Dependency injection seems to be the solution to this and are used by some of the big frameworks around.
I've found Bucket on Github and have messed around it for a while to understand the basics. What I can't get my head around however is when it's appropriate to create a Container?
Making one big container including every possible class that may be needed seems nothing but counter-productive to me and I can't imagine that it is good practice. It seems like the recipe for bad performance at least.
In the alternative, which is to make multiple containers, I still don't get how the ever-stinking Singletons are not needed anymore.
Let's say that I would have the following code:
$session_container = new bucket_Container();
$session_container->create('Database');
$session_container->create('Database_Sessions');
$log_container = new bucket_Container();
$log_container->create('Database');
$log_container->create('Database_Log');
So here we have two containers, or in this case buckets for two totally different usages which are mutual by their dependency on the Database class.
My logic tells me that the above code will create two independent instances of the Database-class, meaning that I still would have to make the Database-class a singleton to ensure that concurrent instances of my database connection isn't occurring?
Is this correct?
I don't know much about the specific lib, but assuming it lets you use a factory, let the factory return the same instance.
Edit: Ok, this is simply on the Bucket GitHub index page.
class MyFactory {
function new_PDO($container) {
return new PDO("mysql:host=localhost;dbname=addressbook", "root", "secret");
}
}
$bucket = new bucket_Container(new MyFactory());
$db = $bucket->get('pdo');
So in your case you could simply do:
class MyFactory {
private $pdo;
function new_Database($container) {
if($this->pdo){
return $this->pdo;
}
return $this->pdo = new PDO("mysql:host=localhost;dbname=addressbook", "root", "secret");
}
}
$factory = new MyFactory();
$session_container = new bucket_Container($factory);
$session_container->create('Database_Sessions');
$log_container = new bucket_Container($factory);
$log_container->create('Database_Log');
Something like that. Doesn't seem like rocket science.
Edit2: I don't have enough rep points to comment on the question (bit silly), but in response to your "modularity" concern: think of the container as the "glue" of your application. Indeed, if you have a large application, you may want to "glue" inside an isolated part of your application only. That is a valid encapsulation concern. But even then you still need a container that handles injection at the highest level of abstraction. If you just create a separate container for every part of your application, you either end up with unneeded duplication of instances, or you have to apply another level of instance management, which doesn't improve the encapsulation in any way: you're still sharing instances between different parts of your application.
My advice would be to use a single container at the bootstrap level. If you want added encapsulation for specific parts of your application (modules, plugins, whatever), use "child containers". A child container inherits the instances from the parent container, but the parent container knows nothing of the child (as far as he's concerned, he's still a bachelor ;)). Could be that Bucket supports this by default, I know other DI containers do. If not, it's really easy to implement using a Decorator. Imagine something like this:
class MyContainerType extends bucket_Container {
private $_parent;
private $_subject;
public function __construct($factory = null, bucket_Container $parent = null){
$this->_parent = $parent;
$this->_subject = new bucket_Container($factory);
}
public function get($key){
$value = $this->_subject->get($key);
if($value){
return $value;
}
return $this->_parent->get($key);
}
/**
* Override and delegation of all other methods
*/
}
Making one big container including every possible class that may be needed seems nothing but counter-productive to me and I can't imagine that it is good practice. It seems like the recipe for bad performance at least.
On the contrary. This is exactly what you would do with a di container. The container will only instantiate objects on demand, so there is virtually no overhead to managing all you singleton-ish classes through it.
The biggest problem with di is to distinguish between shared objects (Things you would usually think of as singletons) and transient objects (Objects that have plenty of instances through a normal application flow.). The former are easily managed through di. The latter don't really fit. Having those two "kinds" of objects clearly distinguished may seem like a bit of a hassle, but is really a highly beneficial side effect of using a di container.
If you are worried about multiple simultaneous connections you can just use mysql_pconnect() or the equivelant for the database you are using. It will check if a connection is already open and use the existing connection if it is.
As far as the container issue, I've seen it done in two ways, which you seem to be aware of both. The first method is to have the framework read your database schema and create classes fore each table. I personally don't like this approach. Symfony is one framework that does this (by using the doctrine ORM).
The more preferred method I've seen is to have a generic container, which basically builds the sql for you given a table, columns and an action. This is the approach taken by codeIgniter:
$query = $this->db->get('mytable');
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);

Categories