【问题标题】:Crons/Jobs in a Symfony 3 projectSymfony 3 项目中的 Cron/Jobs
【发布时间】:2017-10-17 05:41:52
【问题描述】:

我的项目的一个功能包括以两种方式在两个数据库之间同步数据。

  • 从接口。 (用户点击按钮开始同步)
  • 从 cron 脚本自动执行。

我在指定的 Controller 中添加了一个新的 Action 'synchronizeAction',我管理了路由和视图,它工作正常。 问题出在 cron 上:

  1. 我应该将我的 cron 脚本放在哪个位置?
  2. 如何使用我在该 cron 内的 Controller 中创建的方法“synchronizeAction”?

我创建了一个服务并使用它。

<?xml version="1.0" ?>
<container xmlns="...">
    <services>
        <service id="soc_ref.synchro_clients" class="SocRefBundle\Services    \SynchroClient">    
        </service>
    </services>
</container>

我创建了 Services/SynchroClient.php

class SynchroClient 
{

    public function __construct()
    {

    }

    public function synchronize () {
        $ref_db = $this->getDoctrine()->getManager();
        $other_db = $this->getDoctrine()->getManager('other');

        $sql = ' SELECT active, .... ';
        $statement = $other_db->getConnection()->prepare($sql);
        $statement->execute();
        $result = $statement->fetchAll();

        foreach ($result as $entity) {
            $client = new Client();
            $client->setActive($entity['active']);

            $ref_db->persist($client);
        }
        $sql_truncate = ' TRUNCATE TABLE client';
        $statement = $ref_db->getConnection()->prepare($sql_truncate);
        $statement->execute();
        $ref_db->flush();

        return new Response('1');
    }

}

如何使用/注入 entityManager ? $this->getDoctrine()->getManager();只能在控制器中访问。

我刚刚开始symfony开发,谢谢你的帮助:)

【问题讨论】:

    标签: php symfony cron


    【解决方案1】:

    如果我必须这样做,首先我会将业务逻辑转移到服务中。创建命令并从控制器和命令调用服务功能。然后配置 cron 来调用创建的命令。

    【讨论】:

    • 谢谢您的回答,先生,我试图这样做,但我遇到了问题。你能看看我的回复并告诉我该怎么做吗?
    • 你需要创建一个ContainerAwareCommand。您可以在此处了解更多信息:symfony.com/doc/current/… 创建后,您可以使用 $this->getContainer()->get('service_name') 从 DI 容器访问您的服务
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 2018-08-03
    • 2019-05-07
    • 2016-06-17
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    相关资源
    最近更新 更多