如何使用zf-console执行Zend Framework 3操作? [英] How to execute Zend Framework 3 action with zf-console?

查看:110
本文介绍了如何使用zf-console执行Zend Framework 3操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用zf-console执行ZF3动作.
我可以使用zend-mvc-console模块执行此操作,并且工作正常.
例如.
Application/config/module.config.php:

I want to execute ZF3 action with zf-console.
I can do this using zend-mvc-console module and it works fine.
For example.
Application/config/module.config.php:

'console' => [
    'router' => [
        'routes' => [
            'cronroute' => [
                'options' => [
                    'route'    => 'sync',
                    'defaults' => [
                        'controller' => Controller\ConsoleController::class,
                        'action' => 'syncEvents'
                    ]
                ]
            ]
        ]
    ]
],

Application/src/Controller/ConsoleController.php

Application/src/Controller/ConsoleController.php

class ConsoleController extends AbstractActionController 
{
    /**
     * Entity manager.
     * @var Doctrine\ORM\EntityManager
     */
    private $entityManager;

    /**
     * User Manager
     * @var Application\Service\UserManager 
     */
    private $userManager;

    /**
     * Constructor. 
     */
    public function __construct($entityManager, $userManager)
    {
        $this->entityManager = $entityManager;
        $this->userManager = $userManager;
    }

    public function syncAction() 
    {
        $response = $this->userManager->syncUserInfo();

        return $response ? 'Sync Success' : 'Failed to sync';
    }
}

但是它说它将被弃用:
https://zendframework.github.io/zend-mvc-console/intro/#不推荐使用

建议使用zfcampus的zf-console:
https://github.com/zfcampus/zf-console

但是我找不到执行Controller动作或使用我的构建服务(如UserManager)的方法.

下面是构建Zend应用程序并检索服务管理器的示例:

But it says that it will be deprecated:
https://zendframework.github.io/zend-mvc-console/intro/#deprecated

It suggest to use zf-console from zfcampus:
https://github.com/zfcampus/zf-console

But I cannot find a way to execute Controller action or to use my build services (like UserManager).

There is example to build Zend Application and retrieve Service manager:

use Zend\Console\Console;
use Zend\Console\ColorInterface as Color;
use ZF\Console\Application;
use ZF\Console\Dispatcher;

chdir(dirname(__DIR__));

require __DIR__  . '/../vendor/autoload.php'; // Composer autoloader 

$application = Zend\Mvc\Application::init(require 'config/application.config.php');
$services    = $application->getServiceManager();

$buildModel = $services->get('My\BuildModel');

是否可以通过它执行控制器操作?还是可以加载UserManager服务?
我试图获取我的UserManager:

Is there a way to execute Controller action with it? Or Can I load my UserManager service?
I tried to get My UserManager:

$buildModel = $services->get('Application\Service\UserManager');

但收到错误:

PHP Fatal error:  Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message 'Unable to resolve service "Application\Service\UserManager" to a factory; are you certain you provided it during configuration?' in /var/www/html/vendor/zendframework/zend-servicemanager/src/ServiceManager.php:687

推荐答案

zend-mvc-console模块确实处于弃用的边缘.就像您一样,我尝试实现zfcampus/zf-console.由于mvc-console模块似乎(几乎)已被弃用,因此我建议您在控制台工作中使用与(mvc)控制器不同的东西.我使用了一个可以处理调用的类(以zf-console期望的方式).

The zend-mvc-console module does seem to be on the edge of deprecation. Just like you I was trying to implement zfcampus/zf-console. Since the mvc-console module seems to be (almost) deprecated, I suggest you use something different than (mvc) controllers for your console work. I used a class that can handle the call (in a way zf-console expects).

这是我为项目工作的一个虚拟示例;

This is a dummy example I was working on for my project;

这是在命令行上调用的脚本:

This is script that is called on the command line:

use Zend\Console\Console;
use Zend\ServiceManager\ServiceManager;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\Glob;
use ZF\Console\Application;
use ZF\Console\Dispatcher;

require_once __DIR__ . '/vendor/autoload.php'; // Composer autoloader

$configuration = [];
foreach (Glob::glob('config/{{*}}{{,*.local}}.php', Glob::GLOB_BRACE) as $file) {
    $configuration = ArrayUtils::merge($configuration, include $file);
}

// Prepare the service manager
$smConfig = isset($config['service_manager']) ? $configuration['service_manager'] : [];
$smConfig = new \Zend\Mvc\Service\ServiceManagerConfig($smConfig);

$serviceManager = new ServiceManager();
$smConfig->configureServiceManager($serviceManager);
$serviceManager->setService('ApplicationConfig', $configuration);

// Load modules
$serviceManager->get('ModuleManager')->loadModules();

$routes = [
    [
        'name' => 'dumb',
        'route' => '[--foo=]',
        'description' => 'Some really cool feature',
        'short_description' => 'Cool feature',
        'options_descriptions' => [
            'foo'   => 'Lorem Ipsum',
        ],
        'defaults' => [
            'foo'   => 'bar',
        ],
        'handler' => function($route, $console) use ($serviceManager) {
            $handler = new \Application\Command\DumbCommand();
            return $handler($route, $console);
        }
    ],
];

$config = $serviceManager->get('config');
$application = new Application(
    $config['app'],
    $config['version'],
    $routes,
    Console::getInstance(),
    new Dispatcher()
);

$exit = $application->run();
exit($exit);

处理程序函数可以使用服务管理器向命令处理程序注入任何依赖项:

The handler function can use the service manager to inject any dependencies to the command handler:

'handler' => function($route, $console) use ($serviceManager) {
    /** @var \Doctrine\ORM\EntityManager $entityManager */
    $entityManager = $serviceManager->get(\Doctrine\ORM\EntityManager::class);
    /** @var mixed $repository */
    $contactRepository = $entityManager->getRepository(\Application\Entity\Contact::class);
    $handler = new \Application\Command\DumbCommand($contactRepository);
    return $handler($route, $console);
}

命令类放置在Command文件夹中,如下所示:

The command class is placed in a Command folder, it looks like:

<?php

namespace Application\Command;

use Application\Entity\Contact;
use Application\Repository\ContactRepository;
use Zend\Console\Adapter\AdapterInterface;
use ZF\Console\Route;

class DumbCommand
{
    /** @var ContactRepository */
    private $contactRepository;

    public function __construct($contactRepository)
    {
        $this->contactRepository = $contactRepository;
    }

    /**
     * @param Route $route
     * @param AdapterInterface $console
     * @throws \Doctrine\ORM\ORMException
     */
    public function __invoke(Route $route, AdapterInterface $console)
    {
        $console->writeLine('Bob was here');
        foreach ($this->contactRepository->findAll() as $item) {
            /** @var Contact $item */
            $console->writeLine($item->getFirstName() . ' was here');
        }
    }
}

(

这篇关于如何使用zf-console执行Zend Framework 3操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆