Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Symfony 2 component in non-Symfony project?

For getting XLIFF/2 support in PHP, in another answer, it was suggested to use the Symfony 2 Translation component.

So I downloaded it from Github into a directory ../vendor/ and naively tried to use it:

<?php

    require_once '../vendor/Symfony/Component/Translation/Translator.php';
    require_once '../vendor/Symfony/Component/Translation/MessageSelector.php';
    require_once '../vendor/Symfony/Component/Translation/Loader/ArrayLoader.php';

    use Symfony\Component\Translation\Translator;
    use Symfony\Component\Translation\MessageSelector;
    use Symfony\Component\Translation\Loader\ArrayLoader;

    $translator = new Translator('fr_FR', new MessageSelector());

This doesn’t work as other components would need to be loaded:

PHP Fatal error:  Interface 'Symfony\\Component\\Translation\\TranslatorInterface' not found in /home/ec2-user/layout/vendor/Symfony/Component/Translation/Translator.php on line 25

Now, I could manually add a require_once for every file, until all dependencies are met, but I’m not sure if that’s the proper approach.

How do I use a single Symfony 2 component in a non-Symfony project? Is that a bad idea?

like image 800
feklee Avatar asked Dec 26 '22 12:12

feklee


2 Answers

Manage your dependencies with composer.

First create a composer.json file in your project folder :

{
    "require": {
        "symfony/translation": "2.4.*"
    }
}

Then download composer and run it :

wget http://getcomposer.org/composer.phar
php composer.phar install

You can now use your component by importing the composer autoloader :

<?php

    require_once('vendor/autoload.php');

    use Symfony\Component\Translation\Translator;
    use Symfony\Component\Translation\MessageSelector;
    use Symfony\Component\Translation\Loader\ArrayLoader;

    $translator = new Translator('fr_FR', new MessageSelector());
    $translator->setFallbackLocales(array('fr'));
    $translator->addLoader('array', new ArrayLoader());
    $translator->addResource('array', array(
        'Hello World!' => 'Bonjour',
    ), 'fr');

    echo $translator->trans('Hello World!')."\n";
like image 186
ncrocfer Avatar answered Jan 07 '23 13:01

ncrocfer


What about using Composer to manage your dependencies.

The point here is that it also manages autoloading,

From the documentation,

Autoloading#

Besides downloading the library, Composer also prepares an autoload file that's capable of autoloading all of the classes in any of the libraries that it downloads. To use it, just add the following line to your code's bootstrap process:

require 'vendor/autoload.php';
like image 20
Ahmed Siouani Avatar answered Jan 07 '23 14:01

Ahmed Siouani