user1961082
user1961082

Reputation: 1035

Symfony2 Dependency Injection / Service Container

I'm pretty new to Symfony2 and have built a custom CMS which has various sections such as user management, page management, image library etc. I want to log all activity within the CMS, therefore thought it would be best to create a centralised class to store the activity so that I can call it from any section.

I've been having a look at dependency injection and service container but struggling to figure out what the difference is? If any?

I've setup the following service but would like feedback on if this is the best method:

# app/config/config.yml
# AdminLog Configuration
services:
    admin_log:
        class:        xyz\Bundle\CoreBundle\Service\AdminLogService
        arguments:    [@doctrine.orm.entity_manager]

Below is my class:

<?php
namespace xyz\Bundle\CoreBundle\Service;
use xyz\Bundle\CoreBundle\Entity\AdminLog;

class AdminLogService
{
    protected $em;

    public function __construct(\Doctrine\ORM\EntityManager $em)
    {
        $this->em = $em;
    }

    public function logActivity($controller, $action, $entityName, $note)
    {
        $adminLog = new AdminLog(
            1,
            $controller,
            $action,
            $entityName,
            $note
        );
        $this->em->persist($adminLog);
        $this->em->flush();
    }

}

I will then call this from any controller within the CMS using the following:

$this->get('admin_log')->logActivity('Website', 'index', 'Test', 'Note here...');
  1. Is this the best method?
  2. Should the class be inside a 'Service' directory within the bundle as I have done?
  3. What is the DependencyInjection folder for?

Thanks

Upvotes: 2

Views: 1389

Answers (1)

Wouter J
Wouter J

Reputation: 41934

Dependency Inction means that you pass objects into a class, instead of initializing it in the class. A Service Container is a class which helps you managing all these services (classes which have dependencies).

Your questions:

Is this the best method?

Yes, except for the namespace.

Should the class be inside a 'Service' directory within the bundle as I have done?

No, it can live in any namespace. You should put it in a logical namespace, such as MyBundle\Logger.

What is the DependencyInjection folder for?

It's meaned for 3 types of classes: Extension, Configuration and Compiler passes.

Upvotes: 3

Related Questions