문제

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?

도움이 되었습니까?

해결책

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";

다른 팁

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';
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top