I've been reading about Dependency Injection but the examples I've found just look like bad code to me, so my main question is am I right in thinking it is bad code, or am I misunderstanding the purpose of it, and is my example any better?
class Photo {
protected $db;
public function __construct()
{
$this->db = DB::getInstance();
}
}
So this is bad code, and the suggestion of Dependency Injection, due to the multitude of setters that might be created if we explicitly set every variable, is:
class Container {
protected $db;
public static newPhoto()
{
$photo = new Photo;
$photo->setDB(static::$db);
$photo->setConfig();
$photo->setResponse();
return $photo;
}
}
$photo = Container::newPhoto();
But correct me if I'm wrong, we've just built a class whose sole responsibility it is to build another class, seems quite pointless, and we are using static methods which is apparently a very bad idea.
The one benefit that I do see, which surprisingly to me isn't mentioned is that we can now test the Photo class independently by using the setters, whilst in the first example we couldn't.
Something like this makes more sense to me:
class Photo {
protected $db;
protected $config;
protected $response;
public function __construct($dbConn=null,$config='123',$response=true)
{
if(is_null($dbConn))
$this->db = DB::getInstance();
else
$this->db = $dbConn;
...etc
}
}
$photo = new Photo($dbConn);
The class builds itself, there is no need for the static method to actually be called, the class can be tested with dummy data if values are used otherwise it falls back on defaults (which seems to be the only point of the Container class), and the dependencies are still somewhat obvious as opposed to the Container.
The goal of Dependency Injection pattern is to decouple how objects that work together are constructed. In your example, it is not the concern of the Photo class to know how to construct a DB instance, but only to use a DB instance to achieve its goals.
The obvious advantage that you already noticed is in testing where you can easily pass mock DB instance if you want to test just the Photo functionality. But you can think also about connection pooling for example where a container has a pool of DB instances and pass one of them to your Photo object for doing its work. When the Photo life-cycle ends the DB instance is returned to the pool and used elsewhere.
The implementation of this pattern can be achieved using constructors with arguments, setters, annotations (at least in Java) and even XML configuration files. In the case of annotations or XML configuration files a container will parse that information create the appropriate needed objects and inject them in the client class.
What you describe at C1 and C2 is a factory class that exposes static methods for obtaining Photo instances. This is a very common pattern used in many places in Java.
I don't know where you leaned about the DI, but the resources seem quite questionable. Instead you should begin by watching this lecture, followed by article from Martin Fowler. Maybe supplemented by this short video.
class Container {
protected $db;
public static newPhoto()
{
$photo = new Photo;
$photo->setDB(static::$db);
$photo->setConfig();
$photo->setResponse();
return $photo;
}
}
$photo = Container::newPhoto();
This is not implementing dependency injection. It actually is just an example of poorly implemented static factory method (anti)pattern. Especially the magical methods $photo->setConfig() and $photo->setResponse() which apparently do some work, but receive no parameters.
And then there is this code:
class Photo {
protected $db;
protected $config;
protected $response;
public function __construct($dbConn=null,$config='123',$response=true)
{
if(is_null($dbConn))
$this->db = DB::getInstance();
else
$this->db = $dbConn;
...etc
}
}
$photo = new Photo($dbConn);
Instead of just assigning values, you decide to hide the dependencies of it, and, if they are not provided, to take them from global scope. And of course, your constructor ends up containing quite a log of computation. Thus making it untestable.
Oh .. and then there is the magical boolean value. Whenever where is such a parameter assigned to a class in constructor, it is a clear sign that you actually needed two different classes, which implement same interface.
So.. to answer your question:
I've been reading about Dependency Injection but the examples I've found just look like bad code to me, so my main question is am I right in thinking it is bad code, or am I misunderstanding the purpose of it, and is my example any better?
No. Your example is not better. You just combined the worst parts from both your earlier code example in single class definition.
Related
I was wondering if there's a good way to implement the registry pattern in PHP, let me be more clear:
I do know that a Registry is used when you need to keep track of the object you instantiate in order to reuse them and not re-instantiate them again from script to script, e.g. I have a Database class that I want to instantiate only once and then use for all my scripts and I do not want to re-instantiate it again and again. Another example could be a User class that represents an instance of the currently logged in user. I could not use a Singleton in this case, cause e.g. I need another User instance for example when I want to retrieve a friend of the currently logged in user etc.
So I came up with the idea that the Registry better suits this kind of needs in such cases.
I also know that there are two ways of implementing it, or better two ways in order to access the stored instances:
Explicitly or externally, meaning that the Registry should be called every time you need to recover an instance inside your scripts or you need to put an instance inside of it;
Implicitly or internally, meaning that you make kind of an abstract class with a getInstance() method that returns an instance with the get_called_class() late static binding feature, adds it to the registry and then return that instance from the registry itself taking care that if a $label parameter is passed to the getInstance() method, then that particular instance from the registry will be returned. This approach is kinda transparent to the consumer and in my opinion is cleaner and neater (I'll show both implementations, though).
Let's take a basic Registry (really simple implementation, just an example took from a book):
class Registry {
static private $_store = array();
static public function set($object, $name = null)
{
// Use the class name if no name given, simulates singleton
$name = (!is_null($name)) ? $name: get_class($object);
$name = strtolower($name);
$return = null;
if (isset(self::$_store[$name])) {
// Store the old object for returning
$return = self::$_store[$name];
}
self::$_store[$name]= $object;
return $return;
}
static public function get($name)
{
if (!self::contains($name)) {
throw new Exception("Object does not exist in registry");
}
return self::$_store[$name];
}
static public function contains($name)
{
if (!isset(self::$_store[$name])) {
return false;
}
return true;
}
static public function remove($name)
{
if (self::contains($name)) {
unset(self::$_store[$name]);
}
}
}
I know, Registry could be a Singleton, so you never have two Registry at the same time (who needs them someone could think, but who knows).
Anyway the externally way of storing/accessing instances is like this:
$read = new DBReadConnection;
Registry::set($read);
$write = new DBWriteConnection;
Registry::set($write);
// To get the instances, anywhere in the code:
$read = Registry::get('DbReadConnection');
$write = Registry::get('DbWriteConnection');
And internally, inside the class (taken from the book) when getInstance is called:
abstract class DBConnection extends PDO {
static public function getInstance($name = null)
{
// Get the late-static-binding version of __CLASS__
$class = get_called_class();
// Allow passing in a name to get multiple instances
// If you do not pass a name, it functions as a singleton
$name = (!is_null($name)) ?: $class;
if (!Registry::contains($name)) {
$instance = new $class();
Registry::set($instance, $name);
}
return Registry::get($name);
}
}
class DBWriteConnection extends DBConnection {
public function __construct()
{
parent::__construct(APP_DB_WRITE_DSN, APP_DB_WRITE_USER, APP_DB_WRITE_PASSWORD);
} }
class DBReadConnection extends DBConnection {
public function __construct()
{
parent::__construct(APP_DB_READ_DSN, APP_DB_READ_USER,APP_DB_READ_PASSWORD);
}
}
Apparently referring to the registry indirectly (second case) seems more scalable for me, but what if some day I would need to change the registry and use another implementation, I would need to change that calls to Registry::get() and Registry::set() inside the getInstance() method in order to suit the changes or is there a smarter way?
Did someone of you came across this problem and found an easy way to interchange different registries depending on the type of application on the complexity etc.?
Should be a configuration class the solution? Or is there a smarter way to achieve a scalable registry pattern if it is possible?
Thanks for the attention! Hope for some help!
First of all. It's great that you spotted the problem of your approach by yourself. By using a registry you are tight coupling your classes to the registry where you pull your dependencies from. Not only that, but if your classes have to care about how they are stored in the registry and get grabbed from it (in your case every class would also implement a singleton), you also violate the Single-Responsibility-Principle.
As a rule of thumb keep in mind: Accessing objects globally from within a class from whatever storage will lead to tight coupling between the class and the storage.
Let's see what Martin Fowler has to say about this topic:
The key difference is that with a Service Locator every user of a service has a dependency to the locator. The locator can hide dependencies to other implementations, but you do need to see the locator. So the decision between locator and injector depends on whether that dependency is a problem.
and
With the service locator you have to search the source code for calls to the locator. Modern IDEs with a find references feature make this easier, but it's still not as easy as looking at the constructor or setting methods.
So you see it depends on what you are building. If you have a small app with a low amount of dependencies, to hell with it, go on with using a registry (But you absolutely should drop a classes behavior to store itself into or getting grabbed from the registry). If that's not the case and you are building complex services and want a clean and straightforward API define your dependencies explicitly by using Type Hints and Constructor Injection.
<?php
class DbConsumer {
protected $dbReadConnection;
protected $dbWriteConnection;
public function __construct(DBReadConnection $dbReadConnection, DBWriteConnection $dbWriteConnection)
{
$this->dbReadConnection = $dbReadConnection;
$this->dbWriteConnection = $dbWriteConnection;
}
}
// You can still use service location for example to grab instances
// but you will not pollute your classes itself by making use of it
// directly. Instead we'll grab instances from it and pass them into
// the consuming class
// [...]
$read = $registry->get('dbReadConnection');
$write = $registry->get('dbWriteConnection');
$dbConsumer = new DbConsumer($read, $write);
Should be a configuration class the solution? Or is there a smarter way to achieve a scalable registry pattern if it is possible?
That approach is encountered very often and you maybe have heard something about a DI-Container. Fabien Potencier writes the following:
A Dependency Injection Container is an object that knows how to instantiate and configure objects. And to be able to do its job, it needs to knows about the constructor arguments and the relationships between the objects.
The boundaries between a service locator and a DI-Container seem to be pretty blurry but I like the concept to think about it like that: A Service Locator hides the dependencies of a class while a DI-Container does not (which comes along with the benefit of easy unit testing).
So you see, there is no final answer and it depends on what you are building. I can suggest to dig more into the topic since how dependencies are managed is a core concern of every application.
Further Reading
Why Registry Pattern is antipattern. And what is alternative for it.
Service Locator is an Anti-Pattern
Do you need a Dependency Injection Container?
Through my multiple studies I have come across the factory method of setting session and database objects which I have been using while in development. What I am wondering is, putting aside personal preference (although I will soak in any opinions anyone has), does this general method work, and is it efficient (meaning, am I using it correctly)? If it is not, do you have suggestions for how to improve it?
Background
I created the code this way so as to pass a database and session object to the class upon calling the class. I wanted to be able to pass along the relevant objects/references so that they could be used.
The Call Class
This class is meant to call static functions, like so:
class CALL {
public static $_db, $_session;
public status function class1() {
$function = new class1();
$function->set_session(self::$_session);
$function->set_database(self::$_db);
return $function;
}
public status function class2() {
...
}
...
}
The _set class
class _set {
public $_db, $_session;
public function __construct() { ... }
public function set_database($_db) {
$this->_db = $_db;
}
public function set_session($_session) {
$this->_session = $_session;
}
}
Now the classes referenced.
class class1 extends _set {
function __construct() { ... }
function function1() { return "foo"; }
...
}
So, moving forward, the classes would be called using CALL::class1 or CALL::class2. After that, they can be accessed as per usual, aka:
CALL::$_db = $database->_dbObject;
CALL::$_session = $_SESSION;
$class1 = CALL::class1;
echo $class1->function1(); //prints "foo".
Read about Dependency Injection . Small suggestion from my point of view, you should never create objects like $db or $session inside other objects. You should rather inject them through constructor or setter method. It will make your code less dependant on a specific classes and it will be easier to replace all dependencies almost without refactoring (actually without one if you know hot to use interfaces).
If anyone stumbles on this, I will share with you what my solution was.
Although this exercise helped me to learn a lot, and I am sure I could take the time to create a VERY highly functional factory/Container, because this is not integral to my program and not even unique, I finally bowed to the age old wisdom of not repeating something that has already been done.
I utilized Pimple, a lightweight library that uses PHP closures to create function calls. Now, I can haave the flexibility of determining which dependency injections I want, but I also only need to inject them once. Future calls, even when they create new instances, will replicate them. While I think that, in theory, my project was workable as it was, it did indeed have the unfortunate issue of requiring you to go into the container to make changes. With Pimple I do not need to do that. So I've tossed by Container class and picked up a lightweight program from the maker of Symfony. While this may not be the best answer for everyone, it was for me. Cheers!
With regards to using class objects within another class what is the best practice? To pass the class objects in the class _construct statement or create a new class object?
Example 1:
class Foo {
private $bar;
public function __construct($bar){
$this->bar = $bar;
}
}
Or Example 2 :
class Foo {
private $bar;
public function __construct(){
$this->bar= NEW bar;
}
}
I'm aware that obviously it's taken for granted that the class file must already be included somewhere else, and in the first instance a class object of this type would need to exist already, but I want to know what the advantages are each method are, as I have a lot of classes I need to code that use a database object and I need the best way to pass this into the classes. Is there a third option that's better than these two?
From what I can understand, the advantage of the first one could be a few less lines of coding and in the case of a DB, not having a new connection created. The second one might be better however because it's more self contained? Anyhow I thought I'd ask the experts.
The first. (This approach is called Dependency Injection).
The constructor asks for whatever the object in questions needs in order to work. This way, it's pretty clear from the methods alone (what they need, and what they return), what it does. Without even looking at the source code.
A way to improve your code would be to introduce type hinting into your method:
class Foo {
private $bar;
public function __construct(Bar $bar){
$this->bar = $bar;
}
}
So that only Bar objects may be passed in.
Advantages of Dependency Injection
Very readable.
Ability to tell the method's dependencies without viewing the source code.
Makes Unit Testing possible.
*Saves kittens from God's wrath.
* Disclaimer: No kittens were harmed during the manifestation of this answer
You should go for option 1, as this is the simplest form of dependency injection.
In option 1:
classes are independent of each other
classes can be tested independent, using a mock for the bar class
In general, I'd chime in with the DI crowd for reasons outlined in How to Think About the “new” Operator with Respect to Unit Testing:
But the reason why Dependency Injection is so important is that within unit-tests you want to test a small subset of your application. The requirement is that you can construct that small subset of the application independently of the whole system. If you mix application logic with graph construction (the new operator) unit-testing becomes impossible for anything but the leaf nodes in your application.
Separating your code into creator graphs and collaborator graphs will help to keep your code maintainable and testable. Even better, code against interfaces and it will be very easy to swap out concrete implementations against other ones. This makes changing your code simple, because you don't have to wade through your code hunting for hardcoded dependencies.
For instance, assuming your Bar requires a Logger, you'd do
class Foo
{
private $logger;
public function __construct(LogInterface $logger)
{
$this->logger = $logger;
}
}
And then you pass in any concrete implementation implementing that LogInterface, like a Database Logger or a StdOutLogger or maybe a Composite Logger holding both of these. Another example would be a Database object. You can create that once in your bootstrap and then pass it to the objects making use of it.
When in doubt, go with Dependency Injection.
However, you don't always have to inject stuff. It depends whether the object (your Bar) is an Injectable or a Newable. To quote Misko Hevery:
An Injectable class can ask for other Injectables in its constructor. […] Injectables tend to have interfaces since chances are we may have to replace them with an implementation friendly to testing. However, Injectable can never ask for a non-Injectable (Newable) in its constructor. This is because DI framework does not know how to produce a Newable. […] Some examples of Newables are: Email, MailMessage, User, CreditCard, Song. If you keep this distinctions your code will be easy to test and work with. If you break this rule your code will be hard to test.
In a nutshell, when you have something that cannot be reasonably injected, because it is based on user-supplied or runtime information, you can new it. This is especially true for Value Objects and Data Types:
class Foo
{
private $storage;
public function __construct()
{
$this->storage = new SplObjectStorage;
}
}
There is no point in injecting SplObjectStorage. It's just a data type.
Others have already answered your question - definitely go with the first approach, which uses Dependency Injection.
I just wanted to chip in with another popular alternative you may not be aware of: using a Dependency Injection Container.
A great, simple example of this is Pimple; developed by Fabien Potencier, the man behind the Symfony frameworks.
Example 3:
# In a bootstrap file...
require_once '/path/to/Pimple.php';
$container = new Pimple();
$container['bar'] = function ($c) {
return new Bar(/** If bar has dependencies, put them here **/);
};
$container['foo'] = function ($c) {
return new Foo($c['bar']);
};
# You'd still inject the service using DI, because it's not good
# practice for your objects to rely directly on the container
class Foo {
private $bar;
public function __construct($bar){
$this->bar = $bar;
}
}
# The difference would be how you call Foo...
$foo = $container['foo'];
# So now your code doesn't need to know about the dependencies, and it's easy
# to change them at any time by making a single change in your configuration
Symfony2 uses a more robust Container, which is also available as a standalone compenent. But Pimple is probably your best bet unless you're developing a large-scale application.
I'd say use the 1st option. While doing so, I'd say programming to abstractions is a better idea than programming to an implementation.
Your first option is a form of aggregation while the second is that of composition. The benefit you would get with abstractions is that your client class that uses class FOO will be able to get FOO to do some activity based on a particular implementation of the interface it decides to send into the constructor..
A C# example below
class Foo {
private IBar bar;
public Foo(IBar obj){
this.bar = obj;
}
public void myFooMethod()
{
bar.ExecuteMethod();
}
}
The class calling FOO
public class MyCallingClass
{
public void CallFooMethod()
{
IBar bar1Obj = new BAR1();
Foo fooObject = new Foo(bar1Obj);
fooObject.ExecuteMethod();
//or
IBar bar2Obj = new BAR2();
fooObject = new Foo(bar2Obj);
fooObject.ExecuteMethod();
//or
IBar bar3Obj = new BAR3();
fooObject = new Foo(bar3Obj);
fooObject.ExecuteMethod();
}
}
Now my calling class can pass any implementation of IBar to the FOO class.
Hope this helped.
Ok, Dependency Injection is wonderful, and helpful and saves kittens, so I'm not going to discuss it in detail.
Instead, I'm going to suggest you implement both solutions:
class Foo {
private $bar;
public function __construct($bar = null){
$this->bar = isset($bar) ? $bar : new Bar();
}
}
That way, you can use the default class by default, and if you need to change the functionality, you can do that too.
I know there are loads of questions on this, I have done quite a bit of reading. I'd like to ask this in context of my project to see what suggestions you may have.
I have quite a large web application with many classes, e.g. users and articles (which i consider to be the main classes) and smaller classes such as images and comments. Now on a page, lets say for example an article, it could contain many instances of images and comments. Makes sense right? Now on say an articles page I call a static method which returns an array of article objects.
That's the background, so here are the questions.
Since building a large amount of the app I came to realise it would be very useful to have a core system class containing settings and shared functions. There for I extended all of my classes with a new core class. Seemed relatively simple and quick to implement. I know CodeIgniter does something similar. I feel now though my app is becoming a bit messy.
Question Is this a good idea? Creating an instance of core is exactly what I want when calling an instance of an article, but what about when i'm creating multiple instances using the static method, or calling multiple images or comments on a page. I'm calling the core class unnecessarily right? Really it only needs to be called once per page (for example the constructor defines various settings from the database, I don't want to this every time, only once per page obviously), but all instances of all classes should have access to that core class. Sounds exactly like I want the singleton approach, but I know that's a waste of time in PHP.
Here's an idea of what my code looks like at this point. I've tried to keep it as simple as I can.
class core {
public function __construct(){
...define some settings which are retrieve from the database
}
public function usefulFunction(){
}
}
class user extends core {
public function __construct(){
parent::__construct();
}
public function getUser($user_id){
$db = new database();
$user = /* Get user in assoc array from db */
$this->__setAll($user);
}
public static function getUsers(){
$db = new database();
$users = /* Get users from database in assoc array from db */
foreach($users as $user) {
$arrUsers[] = new self();
$arrUsers[]->__setAll($user);
}
return $arrUsers;
}
private function __setAll($attributes) {
foreach($attributes as $key => $value)
{
$this->__set($key, $value);
}
}
public function __set($key, $value) {
$this->$key = $value;
}
}
The other issue I'm having is efficiently using/sharing a database connection. Currently each method in a class requiring a database connection creates a new instance of the database, so on a page I might be doing this 5 or 10 times. Something like the dependency injection principle sounds much better.
Question Now if i'm passing the instance of the DB into the new user class, i know I need something like this...
class user{
protected $db;
public function __construct($db){
$this->db = $db;
}
... etc
}
$db = new database();
$user = new user($db);
... but when I want to run the static function users::getUsers() what is the best way to gain access to the database instance? Do i need to pass it as a variable in each static method? (there are many static methods in many classes). It doesn't seem like the best way of doing it but maybe there isn't another way.
Question If extending all of my classes off the core class as suggested in part 1, can I create an instance of the DB there and access that some how?
Question I also have various files containing functions (not oop) which are like helper files. What's the best way for these to access the database? Again i've been creating a new instance in each function. I don't really want to pass the db as a parameter to each one. Should I use globals, turn these helper files into classes and use dependency injection or something different all together?
I know there is lots of advice out there, but most info and tutorials on PHP are out of date and don't ever seem to cover something this complex...if you can call it complex?
Any suggestions on how to best layout my class structure. I know this seems like a lot, but surely this is something most developers face everyday. If you need any more info just let me know and thanks for reading!
You asked in a comment that I should elaborate why it is a bad idea. I'd like to highlight the following to answer that:
Ask yourself if you really need it.
Do design decisions for a need, not just because you can do it. In your case ask yourself if you need a core class. As you already have been asked this in comments you wrote that you actually do not really need it so the answer is clear: It is bad to do so because it is not needed and for not needing something it introduces a lot of side-effects.
Because of these side-effects you don't want to do that. So from zero to hero, let's do the following evolution:
You have two parts of code / functionality. The one part that does change, and the other part that is some basic functionality (framework, library) that does not change. You now need to bring them both together. Let's simplify this even and reduce the frame to a single function:
function usefulFunction($with, $four, $useful, $parameters)
{
...
}
And let's reduce the second part of your application - the part that changes - to the single User class:
class User extends DatabaseObject
{
...
}
I already introduced one small but important change here: The User class does not extend from Core any longer but from DatabaseObject because if I read your code right it's functionality is to represents a row from a database table, probably namely the user table.
I made this change already because there is a very important rule. Whenver you name something in your code, for example a class, use a speaking, a good name. A name is to name something. The name Core says absolutely nothing other that you think it's important or general or basic or deep-inside, or that it's molten iron. No clue. So even if you are naming for design, choose a good name. I thought, DatabaseObject and that was only a very quick decision not knowing your code even, so I'm pretty sure you know the real name of that class and it's also your duty do give it the real name. It deserves one, be generous.
But let's leave this detail aside, as it's only a detail and not that much connected to your general problem you'd like to solve. Let's say the bad name is a symptom and not the cause. We play Dr. House now and catalog the symptoms but just to find the cause.
Symptoms found so far:
Superfluous code (writing a class even it's not needed)
Bad naming
May we diagnose: Disorientation? :)
So to escape from that, always do what is needed and choose simple tools to write your code. For example, the easiest way to provide the common functions (your framework) is as easy as making use of the include command:
include 'my-framework.php';
usefuleFunction('this', 'time', 'really', 'useful');
This very simple tow-line script demonstrates: One part in your application takes care of providing needed functions (also called loading), and the other part(s) are using those (that is just program code as we know it from day one, right?).
How does this map/scale to some more object oriented example where maybe the User object extends? Exactly the same:
include 'my-framework.php';
$user = $services->store->findUserByID($_GET['id']);
The difference here is just that inside my-framework.php more is loaded, so that the commonly changing parts can make use of the things that don't change. Which could be for example providing a global variable that represents a Service Locator (here $services) or providing auto-loading.
The more simple you will keep this, the better you will progress and then finally you will be faced with real decisions to be made. And with those decisions you will more directly see what makes a difference.
If you want some more discussion / guidance for the "database class" please consider to take a read of the very good chapter about the different ways how to handle these in the book Patterns of Enterprise Application Architecture which somewhat is a long title, but it has a chapter that very good discusses the topic and allows you to choose a fitting pattern on how to access your database quite easily. If you keep things easy from the beginning, you not only progress faster but you are also much easier able to change them later.
However if you start with some complex system with extending from base-classes (that might even do multiple things at once), things are not that easily change-able from the beginning which will make you stick to such a decision much longer as you want to then.
You can start with an abstract class that handles all of your Database queries, and then constructs them into objects. It'll be easy to set yourself up with parameterized queries this way, and it will standardize how you interact with your database. It'll also make adding new object models a piece of cake.
http://php.net/manual/en/language.oop5.abstract.php
abstract class DB
{
abstract protected function table();
abstract protected function fields();
abstract protected function keys();
public function find()
{
//maybe write yourself a parameterized method that all objects will use...
global $db; //this would be the database connection that you set up elsewhere.
//query, and then pack up as an object
}
public function save()
{
}
public function destroy()
{
}
}
class User extends DB
{
protected function table()
{
//table name
}
protected function fields()
{
//table fields here
}
protected function keys()
{
//table key(s) here
}
//reusable pattern for parameterized queries
public static function get_user( $id )
{
$factory = new User;
$params = array( '=' => array( 'id' => $id ) );
$query = $factory->find( $params );
//return the object
}
}
You'll want to do your database connection from a common configuration file, and just leave it as a global variable for this pattern.
Obviously this is just scratching the surface, but hopefully it gives you some ideas.
Summarize all answers:
Do not use single "God" class for core.
It's better to use list of classes that make their jobs. Create as many class as you need. Each class should be responsible for single job.
Do not use singletones, it's old technique, that is not flexible, use dependecy injection container (DIC) instead.
First, the the best thing to do would be to use Singleton Pattern to get database instance.
class Db{
protected $_db;
private function __construct() {
$this->_db = new Database();
}
public static function getInstance() {
if (!isset(self::$_db)) {
self::$_db = new self();
}
return self::$_db;
}
}
Now you can use it like db::getInstance(); anywhere.
Secondly, you are trying to invent bicycle called Active Record pattern, in function __setAll($attributes).
In third, why do you wrote this thing in class that extends Core?
public function __construct(){
parent::__construct();
}
Finally, class names should be capitalized.
For dependency injection, I understand that I have to pass an instance of one class to the main instance instead of the main class creating it's own instance, like so (php):
class Class_One {
protected $_other;
public function setOtherClass( An_Interface $other_class ) {
$this->_other_class = $other_class;
}
public function doWhateverYouHaveToDoWithTheOtherClass() {
$this->_other_class->doYourThing();
}
}
interface An_Interface {
public function doYourThing();
}
class Class_Two implements An_Interface {
public function doYourThing() { }
}
class Class_Three implements An_Interface {
public function doYourThing() { }
}
// Implementation:
$class_one = new Class_One();
$class_two = new Class_Two();
$class_three = new Class_Three();
$class_one->setOtherClass( $class_two );
$class_one->doWhateverYouHaveToDoWithTheOtherClass();
$class_one->setOtherClass( $class_three );
$class_one->doWhateverYouHaveToDoWithTheOtherClass();
This is all fine. I know that since both Class_Two and Class_Three both implement An_Interface, they can be used interchangeably in Class_One. Class_One wouldn't know the difference between them.
My question is, is it ever a good idea to, instead of passing an instance to setOtherClass, pass a string such as "Class_Two", and have Class_One's setOtherClass method actually create the instance itself like so:
class Class_One {
...
public function setOtherClass( $other_class_name ) {
$this->_other_class = new $other_class_name();
}
...
}
Does this sort of defeat the purpose of Dependency Injection, or is this completely valid? I thought this type of set up may help me with configuration, where a user can specify which class he wants to use in a string earlier on and this can later be passed to the Class_One..
Actually, writing this out has made me think that it's probably not a good solution, but I'll still post this in case someone can give me some good feedback on why I should/shouldn't do this.
Thanks =)
Ryan
That theoretically defeats the purpose of dependency injection; you are telling Class_One, which depends on An_Interface, which concrete implementation of that interface it should instantiate. That requires Class_One to know how to instantiate ANY An_Interface implementation, tightly coupling Class_One to ALL An_Interface implementations. If you add a new An_Interface Class_Four, you have to go back and tell Class_One how to instantiate a Class_Four.
In PHP, you get away with this AS LONG AS all An_Interface implementations have a parameterless constructor. However, if any implementation needs OTHER dependencies injected, you're screwed; you can't tell Class_One to just new up a Class_Four if a Class_Four needs a Class_Five that Class_One doesn't know about.
Pass an object that's specified by an interface. Otherwise how will you always know with 100% accuracy what it will take to construct the object?
public function __construct(MyInterface $object) {
}
That way, it doesn't matter how you create the object, you just need to know if you can use it how you need to (the interface you're programming against)...
Either way is technically equivalent IMO. The main test to tell if you are doing dependency injection right is to see if you are using any constant strings with "new" or with static method calls. Your code looks good, as long as in the implementation section, the classes can be changed via configuration or some other mechanism. The only downside with passing a string name of a class is that you can't be sure that it implements an specific interface or extends some other object. The checking for this could get messy. However, if your application can handle this issue gracefully, then you should be alright. Passing an actual instantiated object though is the best technique.