rodrigodiez/symfony-rich-console

将依赖注入和事件分发组件集成到非框架Symfony控制台应用程序中

1.0.1 2014-01-15 12:58 UTC

This package is not auto-updated.

Last update: 2024-09-24 02:03:31 UTC


README

此组件将Symfony依赖注入Symfony事件分发组件集成到Symfony控制台应用程序中。

注意:此功能仅适用于处理Symfony控制台独立应用程序,而不是Web框架应用程序。

Scrutinizer Quality Score SensioLabsInsight

示例

    public function run(InputInterface $input, OutputInterface $output)
    {
        // You can access services
        $myService = $this->container->get('my_service');
        $input->writeln('My service says ' . $myService->hello());

        // You can get parameters
        $myParam = $this->container->getParameter('my_param');

        // You can dispatch events and these will be received by their listeners / subscribers
        $event = new Event();
        $this->container->get('event_dispatcher')->dispatch('custom.event', $event);
        $input->writeln('My listeners says ' . $event->getValue());
    }

安装

1. 使用composer下载

rodrigodiez/symfony-rich-console添加到您的composer.json

{
    "require": {
        "rodrigodiez/symfony-rich-console": "dev-master"
    }
}

现在,通过输入以下命令让composer下载组件:

$ php composer.phar update rodrigodiez/symfony-rich-console

2. 创建一个控制台

您需要一个入口点文件来实例化和运行应用程序。您可以在app/console中创建它。

#!/usr/bin/env php

<?php
use Rodrigodiez\Component\RichConsole\Console\Application;

require_once('vendor/autoload.php');

$app = new Application();
$app->run();

请注意,您必须扩展此组件中提供的自定义Application类。

Application类的构造函数接收两个可选参数

  • configPath:包含配置路径的字符串。应用程序将尝试在此处查找所需的parameters.yml文件和其他配置文件。默认为app/config
  • configFilenames:位于$configPath中的文件名数组,您希望将其加载到容器中。例如:array('services.yml')。您通常会在这些文件中定义您的命令服务监听器订阅者等。

2. 创建一个parameters.yml文件

此文件是必需的,它必须位于您的configPath中,并且它必须至少包含以下信息

parameters:
    application_name: your_application_name
    application_version: your_application_version

3. 完成!

现在,您可以通过输入以下命令来执行您的应用程序...

$php app/console

...但结果可能会令人失望。这是因为我们尚未将任何命令注册到应用程序中。

添加配置文件

为了能够定义您的服务(命令也被定义为服务),您需要在configPath中创建一个配置文件,并告诉应用程序加载它

//app/console

//...
$app = new Application(null, array('services.yml'));
//...

注册命令

只需将您的命令注册为服务,并将其标记为console.command

# app/config/services.yml
services:
    command_service:
        class: Your\Namespace\YourCommand
        tags:
            - { name: console.command }

如果您的命令类实现了Symfony\\Component\\DependencyInjection\\ContainerAwareInterface,则容器将被注入,您可以通过其$container属性来检索它。

注册监听器和订阅者

# app/config/services.yml
services:
    listener_service:
        class: Your\Namespace\YourListener
        tags:
            - { name: kernel.event_listener, method: onEventMethod }

    subscriber_service:
        class: Your\Namespace\YourSubscriber
        tags:
            - { name: kernel.event_subscriber }

就这样!

希望这对某人有所帮助。评论、问题报告和pull请求都将受到欢迎 :)