可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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";
回答2:
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';