Dependency Injection when using PHP's built in classes - php

So I know the basics of Dependency Injection. I should pass in my dependencies as method parameters instead of instantiating the objects themselves inside the method.
I was wondering if this also applies to classes that come with PHP, such as DateTime objects or ReflectionClass objects?
For example one of the methods of a class I'm working on needs to know about the properties of a object that is passed in. I wanted to use a ReflectionClass to accomplish the task, but I thought it seemed unnecessary to have to pass a ReflectionClass object as a parameter if the class will always be accessible and relatively unchanged (Unless ReflectionClass changes with newer PHP versions).

It depends on the design requirements of your application.
If you know that your application requires a DateTime for a specific method to function, then pass in a DateTime. If you require custom functionality around a DateTime, then consider sub-classing DateTime and send that.
If you decide to use PHP's type hints in your method signature, consider using an interface instead, so that any object sent will fulfill that contract with the receiving class. This approach can also help insulate your application against incompatible changes in PHP in the future.

Related

Why to use Dependency Injection components in PHP frameworks

When I first saw dependency injection components like PHP-DI, Symfony2 DI, etc., I though, there is a way to automatically inject instance of any class to any just with one instantiation.
So
1. Create instance in root class like $foo = new Foo()
2. And then I can use this instance in any object (like global singleton) without passing reference to constructor or method of the class I want to call from.
But I found out, that basicly I can use Dependency Injection in 2 ways
1. Passing the reference of the instance to constructor
2. Creating container where all objects are located. This container could be injected to other classes, but "This is not recommended".
As both ways can be easily done in pure PHP, the first is clear, the second could be solved with static properties, so why to use PHP-DI or Symfony2 for this work?
Why should you use Dependency Injection over the Singleton pattern?
Let's assume we have a Singleton object named DatabaseConnection which wraps a connection to a MySQL database for us and does some other neat things, who knows. Because reusing code is a good thing, we use this object in a lot of projects.
What if at some point we decide to switch one of our projects from MySQL to another database product? We would have to modify every place where we call the DatabaseConnection object and replace it with our new implementation. Or, we could modify the class itself -- but we still want to use the original one with other projects, so we end up with two implementations with the same name which is just asking for trouble, really.
And what about unit tests? We do those, of course, because we are good developers! But if we unit test a function that uses the database, we don't want the test to actually rely on the database or even change things there. There's no way to replace the DatabaseConnection with a mock object (that just returns static data) because our project is tightly coupled to it.
That's what Dependency Injection does: It helps to prevent tight coupling. If we inject the connection with $someObject->setDatabaseConnection($databaseConnection), we can inject any object there that behaves like the original one. We can inject mock objects, alternative implementations or extensions that inherit the original class.
Now a Dependency Injection Container is just a nice helper to manage object instances and their dependencies more easily, but it's not needed for doing Dependency Injection.

How to use one object in another class : PHP framework

This is my current system for a framework that I'm making:
I create an object upon a request to access a non-existing property, that has the name of an existing class through the __get function defined in the Core class. The Core class extends every class.
So it works like this:
class Someclass extends Core
{
public function classmethod()
{
$this->otherclass->method();
}
}
This works exactly how I want it to work. However, I have no idea (after a lot of frustration) how to edit/create properties of the object, using this system.
So something like this would't work.
$this->view->somevar = "newvalue"; // this doesn't work.
I guess it has to do something with the __set function, but I failed to find out.
I received the following suggestions how to tackle this problem:
Dependency injection, Namespaces, Singleton pattern.
I would love to see how to implement what I'm trying to do using one of these patterns.
I have no idea which to choose in order to achieve my simple problem: Use objects in other classes, so i don't need to put anything into __construct's parameters or using global variables.
I am using __autoload.
I hope i can tackle this problem with your help.
First of all, the architecture you're attempting is extremly bad. Aparently you are using "magic" to create objects attached as properties to other objects. Which is bad, because if you use _get/_set, you will end up in problems sooner rather than later. Also extending from a common parent is a bad thing because it generates huge inheritance trees, and it allows most of the objects to have more than one responsability.
Before starting a framework, you might want to look over: SOLID
Now coming back to your question, if you use __get for getting a value, you can as well use __set for setting a value.
__construct method is there in order to allow you to initialize the object with all the data it needs in order to fulfill his sole purpose. Avoiding the __construct is kinda stupid, and defeats the purpose. You might want to pay attention to the D in SOLID in order to see what Dependency Inversion really is and to understand it.
Using __set loses completely the ability to typehint interfaces and so on. Therefore the code can become really buggy and ijcredibly hard to follow, since the flow is not so well defined, and the allocation is done in the back via magic. Also i can come up with 1 million other reason for which the architecture you are trying to use is wrong, but i will leave that for another time.

understanding Factory method pattern

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

PHP Interfaces: How are they usable in practice?

I'll start by saying that I know how PHP interfaces work and how to "use" them.
My question is rather; how do they become useful in real life applications?
I've been writing PHP for over 3 years now and have never felt the need for an interface. I am writing interfaces more for good practice than for a particular purpose.
I'll provide an example where I've used interfaces in my own real-world experience.
Interfaces are extremely useful when you need to define something like a plugin architecture. Suppose your application accepts authentication plugins, allowing your end user implementers to integrate with their own internal auth infrastructures (LDAP, Shibboleth, some custom auth database, whatever). In order for a plugin to be compatible, it must implement the following methods:
validate_user()
start_user_session()
logout_user()
get_user_details()
If defined in an interface, a class then implements the interface ensuring that the necessary methods are present for compatibility with the plugin architecture.
Unfortunately, PHP does not enforce the return type of interface methods, so you must simply take care to document the expected return functionality of your methods.
They are not so useful - yet. Their main purpose seems to be for type hinting. When you write two separate classes that implement the same interface, you can use that interface in the type hint for a function. That way, you know you got all the methods of that interface available in the object that is passed in the parameter.
Unfortunately, PHP doesn't actually check if any called methods or properties you call on that parameter are actually in that interface, so you can accidentally use an object property that is not available in the interface, causing potential bugs when an object of a different type is passed.
Other languages are much stricter in this situation and will only allow you to use only that functionality that is declared in the interface.
Nevertheless, they are convenient for this purpose in PHP too, and maybe these checks will become stricter in future versions, so it becomes less error prone.
Check out the Standard PHP Library (SPL)
http://php.net/manual/en/book.spl.php
Countable and RecursiveIterator might give you a clue.

Zend AMF custom dispatcher

Is it possible to use a custom dispatcher when using Zend_AMF?
I know I can pass either a class name or an object to setClass() for Zend_AMF.
However, when I pass an object to setClass, it does not seem to store a copy of that object. Instead it worksout the class name and then instantiates a copy of the object itself.
This is a problem as I use the yadif dependency injection container. Objects should be instantiated with constructor dependencies and/or property dependencies.
Since the Zend_Amf dispatcher does all the instantiating, I am not able to inject constructor dependencies and other dependencies to my objects.
If anyone has a strategy as to how I can overcome this without touching any of the code in Zend_AMF, that would be great :)
The solution is to basically build a wrapper around Zend_Amf. The way it is written means that I had to copy most of the code in the handle and _handle() methods. I then had to modify some called methods to point to an instance of Zend_Amf I have created.
Finally, the dispatching was changed so that my own dispatcher was called, and the results returned.
Obviously not the most elegant solution, but hopefully they will rework Zend_AMF to be a bit more extensible in the future and allow us to hook into it much easily.
At the moment, I can still easily drop in an updated version of Zend_AMF into my "vendors" folder without modifying any of the code.

Categories