3

I am all about the best practice of symfony 2 and I would like to integrate a php library into the project. Library is a non bundle, a simple php class with some methods.

My question just follows the following, which DOES NOT have an accepted answer. Anyway from what I read here I decided to autoload the class, but have no idea where should I locate the php file.

Maybe src/MyBundle/DependencyInjection/? I really doubt it since library has no dependency of other services I have.

Should I create a directory like src/MyBundle/Services/ or src/MyBundle/Libraries/?

What is the best practice here?

  • Even if the other question does not have an accepted answer, the most upvoted one is right, what you should warp it on is a service. Because that library is basically providing your application with a specific service to achieve something. – β.εηοιτ.βε May 28 '17 at 21:36
  • So I could locate it inside DependencyInjection directory? –  May 28 '17 at 21:37
  • Nope, inside a Service one: http://symfony.com/doc/current/service_container.html – β.εηοιτ.βε May 28 '17 at 21:52

1 Answers1

0

as mentioned by b.enoit.be create a service from the class.

MyBundle/Service/MyServiceClass.php

<?php

namespace MyBundle\Service;

class MyService
{
...
}

app/config/services.yml

services:
    app.my_service:
        class: MyBundle\Service\MyService

use it e.g. in a controller

MyBundle/Controller/DefaultController.php

<?php

namespace MyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    public function indexAction(Request $request)
    {

        ...

        // get the service from the container
        $yourService = $this->get('app.my_service');

        ...
    }
}
?>
lordrhodos
  • 2,689
  • 1
  • 24
  • 37