Dependency Injection

Dependency Injection is a widely used design pattern. We will define the concepts of this pattern and show a popular PHP implementation with a simple example.

What is DI?

Dependency Injection is a software design pattern that implements Inversion of control by decoupling software modules, introduced by Martin Fowler.

Usually a dependency injection container is used to manage and automate the construction and lifetimes of interdependent objects.

di_uml

Design pattern explanation and Use

Basically, if your class needs an object of other class, in this pattern you pass the dependency object as a constructor parameter or via property setters, instead of invoke factory or create dependency. You make it someone else’s problem.
Example 1:
class MyClass {
    private $objectA;
    public function __construct(ObjectA $object) {
        $this->objectA = $object;
    }
}
Example 2:
class MyClass {
    private $objectA;

    public function setObjectA(ObjectA $object) {
        $this->objectA = $object;
    }
}

In both examples, we don’t care how or where to create the objectA we just use it.

Some popular PHP DI-Container implementations

  • PHP-DI: is an interesting implementation of DI Container that has integration with several frameworks and IDEs like PHPStorm.
  • Symfony DependencyInjection: The DependencyInjection component allows you to standardize and centralize the way objects are constructed in your application.
  • Zend – DI: DI Container implementation for Zend framwork.
  • Pimple: Is a Dependency Injection Container from SensioLabs.

Pimple Presentation

This is an implementation from SensioLabs, and you guessed it, the same guys that created the Symfony libraries.

This is a friendly implemented package, lightweight and easy to use.
To install you just need to add to your composer.json,
$ ./composer.phar require pimple/pimple ~3.0
and you’re ready to use it!
$container = new \Pimple\Container();
Since it implements \ArrayAccess interface, you can store variables and factories as it was an array.
example of parameters:
$container['cookie_name'] = 'SESSION_ID';
an example of factory as a closure:
$container['session'] = $container->factory(function ($c) {
    return new Session($c['session_storage']);
});
It also provides methods to protect parameters, modify services after defined, extends, and more.
For more info refer to Pimple site.

Example Use Cases

Let’s imagine that we want to create factories dynamically based on a JSON configuration like this:
auth_config1
Then we can create a Trait with a method that will fill our container based on an argument that could be an array create from the decode of above JSON.
traits_builder
Here’s how we can use this trait:
di_using
Let’s break down the example above:
the class that implements the __construct method has defined a member attribute, container, that is an instance of Pimple.
Since we are using traits to buildAuthenticator, the result of the foreach block will be assigned into the class container attribute.
Within the build, we need to create a new temporary Pimple object. This is a hack I found to store nested containers.
This is needed because otherwise each time you attempt to add a sub-item within the “AUTHENTICATION” it overrides the previous one.
So once we have created all factories, we just set the temporal container in “AUTHENTICATION” cell of the main container.
To use your created object in the container you just need to do something like that:
$auth = $this->container["AUTHENTICATION"]["mock"];
$result  = $auth->doSomething();

Final Thoughts

This pattern is very useful and widely used these days especially in modern web development, in particular if you see it used in the Angular framework.
Even when you should pick the product that better match your requirements in each case, I can say that I feel very comfortable with Pimple. As I showed, it is very flexible, allowing you to create your own wrap class to customize its behavior and fit your needs.
Hope you enjoyed! Thanks for reading and see you on next posts!

User Auth… What does it really mean?

Auth, a widely use term that can be a bit confused. We will show the meaning and how to work with both definitions as a system.

Auth, a term we can see every where these days. But, what does it really mean?
Honestly, it can be confusing when just saying Auth. Are you talking about authorization or authenticating?
More over, which is the difference between those two terms? Yeah, you got the point!

So now that I have your attention, let’s start by explaining what each is and how they are different and then how we can use both in our systems.

Difference between Authenticate and Authorize

We can roughly say, in the context of computer systems, authenticate is the process that ensures and confirms a user’s identity.

In other hand we can say that authorize or authorization, is the process responsible to determine the level of access that a user has in relation with a resource.

As you may already guessed, both of these should work together as a team.

That’s cool, but how to do that?

Let’s start with Authentication

Okay, starting from a very basic example, where you need to present two keys to the system, for example, username and password, where the first one will identify you and should be unique all system wide, and the other one would confirm that you are who you said you are.

Nowadays there are other architectures that requires multi-level security layers, tokens like oAuth, and so on, but I won’t go deeper on those in this post since this is just an overview.

So, going back to the previous example, you can tackle it at different level. That means, you can go with Sysadmins and request to keep .htaccess and .htpasswd files up to date, or you can choose to tackle at application level.

As you may guess, we will discuss the last one, programmatically. Here, again, we have a bunch of alternatives based on languages, patterns, etc.

My first thought when I had to work on that was, “why should I choose one? why not define an structure that let users select and implement the most appropriate for  each project?”
Yeah, sounds great, but how can I accomplish it? Well, actually is not a big deal (unless you’re trying to reinvent the wheel), is just take a look at already implemented things. The Database layer was my inspiration.

Let me explain how so. I’ve started defining a minimal interface that any Authenticator class should implement, that way I ensure that my controllers will not be broken when I change the configuration.

iauth

As a second step, I’ve added another two interfaces, one that defines requires method to store and retrieve “session” record of current user, and the other that ensure we have at least a “login” method.

storage_interface

Finally, I mixed all this stuff in a basic atuhenticator class, that with the use of Dependency Injection pattern (Pimple in my case) allow us to load based on a config file, any authenticator class that implements our interfaces. That means, I can choose to authenticate against a plain text file, database record or oAuth server like Facebook or Twitter, I just need to implement the logic for the selected service and put it in a config file.

mock_auth

And what about Authorization?

The good news is there’s a lot of alternatives. The bad news is that most of then are not implemented for all languages, instead, it seems that each programming language pick one and discard the other.

Don’t worry, most of them can be categorized in one of those big groups:

  • Role-based access control

from wikipedia

In computer systems security, role-based access control (RBAC) is an approach to restricting system access to authorized users. It is used by the majority of enterprises with more than 500 employees, and can implement mandatory access control (MAC) or discretionary access control (DAC). RBAC is sometimes referred to as role-based security.

Role-based-access-control (RBAC) is a policy neutral access control mechanism defined around roles and privileges.

  • Access Level Control

from wikipedia

An access control list (ACL), with respect to a computer file system, is a list of permissions attached to an object. An ACL specifies which users or system processes are granted access to objects, as well as what operations are allowed on given objects. Each entry in a typical ACL specifies a subject and an operation. For instance, if a file object has an ACL that contains (Alice: read,write; Bob: read), this would give Alice permission to read and write the file and Bob to only read it.

  • Identity Management

from wikipedia

In computer security, identity and access management (IAM) is the security and business discipline that “enables the right individuals to access the right resources at the right times and for the right reasons”. It addresses the need to ensure appropriate access to resources across increasingly heterogeneous technology environments and to meet increasingly rigorous compliance requirements.

In my case, I based on Ruby On Rails’ CanCan gem. Is very nice the way they implemented the “ability” class to grant users and groups the access to specific resource.
This time I’ve based on AC\Kilinka (compose package from American Council) and basically extended it to cover my needs.
Let’s breakdown a bit to make things more clear, there are two big parts, Authorizer and Guard, and two interface that defines them.
The first one, GuardInterface define four basic methods that will be responsible for get and check policies related with an specific resource, the other one, AuthorizerInterface, has two method, one for register guards and “can”, that decides if an action on a resource is permitted.
kalinka_guardinterface
kalinka_authorizerinterface

 

This package also provides some basic implementations. I’ve chosen RoleAuthorizer that better match to my needs, because users used to have a role associated. However, you can use a SimpleAuthorizer that allows you to allow/deny access by user instead of group.

The main difference is the way you config your permissions, here’s an example of what I did in a JSON format:
auth_json

Final thoughts

I have presented a brief overview about how you can identify users and manage permissions to your app resources.
Hope you enjoyed, thanks for reading, and stay tuned in this blog because we will bring you a new Erdiko packages that implements those things, soon!