Tuesday, July 28, 2015

Symfony - Add custom common library and business logic

In the Symfony2 world, this is clearly belonging to a service. Services are in fact normal classes that are tied to the dependency injection container. You can inject them the dependencies you need.

Create a LibraryBundle:

# php app/console generate:bundle --namespace=Foo/LibraryBundle --format=yml

Create the Utils directory:

# mkdir -p src/Foo/LibraryBundle/Utils

Create the Common.php class:

# vim src/Foo/LibraryBundle/Utils/Common.php

<?php

namespace Foo\LibraryBundle\Utils;

class Common
{
    public function helloWorld()
    {
        return 'Hello World!';
    }
}

Register the service to symfony dependecy container:

# vim app/config/services.yml

services:
    service_foo_lib:
        class: Foo\LibraryBundle\Utils\Common

Call your custom function in a controller:

# vim src/Foo/DemoBundle/Controller/DefaultController.php

$str = $this->get('service_foo_lib')->helloWorld();

Reference:

http://stackoverflow.com/questions/10336401/symfony2-global-functions
http://symfony.com/doc/current/cookbook/bundles/best_practices.html
http://symfony.com/doc/current/best_practices/business-logic.html
http://stackoverflow.com/questions/9759096/symfony2-where-to-place-custom-helper-classes

No comments: