PHP Classes

File: README.md

Recommend this page to a friend!
  Classes of Saiik on   Dependency Injection Container   README.md   Download  
File: README.md
Role: Documentation
Content type: text/markdown
Description: Documentation
Class: Dependency Injection Container
Register and get service container classes
Author: By
Last change: typo
Date: 7 years ago
Size: 2,263 bytes
 

Contents

Class file image Download

Container

Container gives you a small dependency injetion to use in your projects

Installation

Run 'composer require saiik\container' and include your autoload.php

Usage

The container class needs at least 1 parameter. The first parameter defines the "namespace" for your container. The 2nd one is a configuration array.

Example:

$container = new saiik\Container(
    'app', 
    [
        'mockup' => true,
        'cache' => 'var/cache/proxies/%s.php'
    ]
);

Register a new instance

To register a new instance you can do it in 2 ways.

__When your class has dependencies on other classes, it will resolve them automatically.__

_In case you have dependencies on interfaces or an abstract class, you can set "mockup" in your configuration to true and it will mock up your interface / abstract class._

Using the register method

You can use the register method. This method expects at least 2 parameters.

  1. The name which will be used to store this instance.
  2. The name of the class
  3. Arguements such as string parameters or something else for the constructor (or method)

Example:

$container->register('controller', Controller::lass);

With args:

$container->register('view', Blade::class, ['templatePath' => __DIR__]);

Using the container object as an array

Also you can handle the container object as an array and register objects without any functions.

Example:

$container['contoller'] = Controller::class;

With args:

$container['view'] = [
    Blade::class,
    [
        'templatePath' => __DIR__
    ]
];

Get a stored instance

To get one instance stored in the container just run this simple function:

$container->get('controller');

And you get your instance.

Full example

$container = new saiik\Container(
    'app', 
    [
        'mockup' => false
    ]
);

class GetMe {

    public function helloWorld() {
        echo "Hello!";
    }

}

class Test {

    protected $test;

    public function __construct(GetMe $class) {
        $this->test = $class;
    }  

    public function test() {
        return $this->test;
    }

}

$container['test'] = Test::class;

$container->get('test')->test()->helloWorld();