evista / compress
WordPress 的 Composer 包管理器集成
Requires
- php: >=5.5.0
- twig/twig: ~1.0
Requires (Dev)
- phpunit/phpunit: 4.*
- scrutinizer/ocular: ~1.1
This package is auto-updated.
Last update: 2024-09-05 00:19:15 UTC
README
ComPress 是一个 WordPress 插件,它帮助使用懒加载服务容器(依赖注入器)与 Composer。
安装
用法
echo $container->get('twig.templating')->render('index.twig.html', ['hehh' => 'Yeah!']);
文档
ComPress 插件使 Composer 在任何 WordPress 项目中都变得可用。如果您从未听说过它,Composer 是一个具有非常好依赖解析器的 PHP 包管理器,使得使用第三方库变得容易。
Composer 最近改变了 PHP 生态系统,因此您可能需要学习它。如果您想在 WordPress 插件或主题中使用最新的 Twig 模板引擎,您只需要
- 在模块的根目录中运行 composer require twig/twig
- 将新包添加到懒加载服务容器的设置中
之后,可以通过这种方式从任何地方访问 Twig 渲染引擎
echo $container->get('twig.templating')->render('index.twig.html', ['hehh' => 'Yeah!']);
如何将包添加到容器中
每个包的初始化方式都不同,容器帮助在统一的 API 下收集它们,并且它还帮助解耦您的代码(解耦使您的代码更易于维护和稳固)
Twig 的文档说这是安装后实例化 Twig 的方法
$loader = new Twig_Loader_Filesystem('/path/to/templates'); $twig = new Twig_Environment($loader, array( 'cache' => '/path/to/compilation_cache', )); echo $twig->render('index.html', array('name' => 'Fabien'));
因此,容器需要实例化两个类,即 Twig_Loader_Filesystem,并使用它作为参数传递给 Twig_Environment 类,该类可以直接用于渲染。如果定义了两个服务,并使用第一个作为第二个的参数,容器可以轻松解决这个依赖关系
//wp-content/plugins/evista-composer/Composer.php /** * Add service definitions here: * */ public function setUpServices(){ $this->services = [ 'twig.loader' =>[ 'class' => '\Twig_Loader_Filesystem', 'arguments' => [__DIR__.'/views'] ], 'twig.templating' => [ 'class' => '\Twig_Environment', 'arguments' => ['@twig.loader'] ], ]; }
Composer::services 变量包含所有所需信息。每个都需要一个唯一的名称,该名称将标识它们在整个 WordPress 中的身份。这些名称将是服务数组的键,而服务数组的最重要属性是值。
在上面的示例中,“twig.templating”是名称,这是从容器请求它的方式
$templating = $container->get('twig.templating'); $page = $templating->render('index.twig.html', ['hehh' => 'Yeah!']);
在上面的配置数组中,有两个重要的键值对:class 和 arguments。
第一个告诉容器应该使用哪个类来实例化服务(带有命名空间),第二个告诉应该使用什么参数以及顺序。到目前为止,字符串、平面(单级)数组和其它服务都被支持作为参数。
public function setUpServices(){ $this->services = [ 'sample.service' =>[ 'class' => '\SampleService', 'arguments' => ['string', '@other.service', ['first'=>'1', "second" => '2']] ], // .. ]; }
就是这样。修改完 Composer 后,您就可以使用通过 composer 安装的新的包了。
变更日志
请参阅 CHANGELOG 了解最近有哪些更改。
测试
$ phpunit
贡献
请参阅 CONTRIBUTING 了解详细信息。
安全
如果您发现任何与安全相关的问题,请通过电子邮件 sera.balint@e-vista.hu 联系我们,而不是使用问题跟踪器。
致谢
许可
MIT 许可证 (MIT)。请参阅 许可文件 了解更多信息。