Search code examples
phpsymfonybundle

Symfony: so finally how to use custom core PHP library on v4-v5?


So subject is the question. Yes, I've searched this forum and googled too. All I've got - useless Symfony docs and casts, some general advises, cli-s and nothing case specific. Maybe yahoo or duckduck could help better?

Everyone is talking about bundles, about how it is important to create them, probably because under the hood Symfony is pushing users away from custom libraries, but no one is actually explains how to start using a bundle - how to start calling its methods.

No, my library is not a composer or whatever package. No, library methods do not return Response objects. No, I am not dealing with composer or recompilations or cli (I use Composercat). No, I will not put library to github or packagist to load it via composer or whatever because it is private library.

Sorry about emotional off-topic.

About the case: I've put my library into the folder

src/lib/MyLibrary.php

I suspect that library class is autoloaded, because if I do not extend Controller with it (if I declare class MyLibrary instead of class MyLibrary extends Controller) - Symfony spits "class name in use" error.

So question: in my controller how to call library method?

$this->get('MyLibrary') doesn't work.

echo print_r($this) doesn't show MyLibrary in this registry too.

Looks like library file is loaded but not registered and/or instantiated. If it is so, then where to point Symfony to register it?


Solution

  • So most of this question is really about how php manages classes. Not so much about Symfony. But that's okay.

    To start with it would be best to move project/src/lib to just project/lib. Symfony has some scanning stuff going on in the src directory and you really don't want to have your library mixed up in it.

    So:

    # lib/MyLibrary.php
    namespace Roman;
    
    class MyLibrary
    {
        public function hello()
        {
            return 'hello';
        }
    }
    

    Notice that I added a namespace (Roman) just to distinguish your code from Symfony's.

    Now you need to tweak composer.json in order to allow php to autoload your classes:

        "autoload": {
            "psr-4": {
                "App\\": "src/",
                "Roman\\": "lib/"
            }
        },
    

    After adding the Roman line, run "composer dump-autoload" to regenerate the autoload files.

    After that, it's just a question of using regular php inside of your application:

    # src/Controller/DefaultController.php
    namespace App\Controller;
    
    use Roman\MyLibrary;
    use Symfony\Component\HttpFoundation\Response;
    
    class DefaultController
    {
        public function index()
        {
            $myLibrary = new MyLibrary();
            $hello = $myLibrary->hello();
            return new Response($hello);
        }
    }
    

    And that should get your started.