Skip to content
This repository was archived by the owner on Feb 17, 2022. It is now read-only.

7.x 2.x service container

Andy Truong edited this page Jan 29, 2014 · 9 revisions

Service Container [7.x-2.x]

Dependency help our code clean, testable…

The Service Container in this module is built on Pimple.

Basic services

If we defined

# /at_base/tests/atest_base/config/services.yml
services:
  atest_base.service_1:
    class: 'Drupal\atest_base\Service_1'
  atest_base.service_2:
    class: 'Drupal\atest_base\Service_2'
    arguments: ['@atest_base.service_1']

We can get instance of service_2:

$service_2 = at_container('atest_base.service_2');

Tagged services

at_container allow us to can get collection of services which have same tag, weight sorted.

If we defined our service like this:

  atest_base.service_1:
    class: 'Drupal\atest_base\Service_1'
    tags:
      - { name: atest1, weight: -10 }

Then we can get it and similar services (same tag) by this simple PHP code:

$names   = at_container('container')->find('atest1', $return = 'service_name');
$objects = at_container('container')->find('atest1', $return = 'service');

Factory

If our service is hard to created, we can define its factory:

twig.core:
  class: '\Twig_Environment'
  factory_class: '\Drupal\at_base\Twig\Environment_Factory'
  factory_method: getObject

We can also use other service as factory:

factory_service:
  class: My_Factory
my_service:
  class: My_Class
  factory_service: '@factory_service'
  factory_method: 'factoryMethod'

Calls

Call methods after service is created:

twig:
  class: '\Twig_Environment'
  factory_class: '\Drupal\at_base\Twig\Environment_Factory'
  factory_method: getFileService
  arguments: ['@twig.core']
  calls:
    - ['setLoader', ['@twig.file_loader']]

Clone this wiki locally