【发布时间】:2016-04-13 10:29:19
【问题描述】:
我已经阅读了很多关于在 symfony 中使用 pthreads。
我的问题有点类似于该问题中暴露的问题:Multi-threading in Symfony2。
简而言之:我的后端在处理它应该处理的所有数据之前达到超时,然后它无法将答案发送回我的前端。
因此,尝试使用不同的线程似乎是绕过该问题的(一种)解决方案(直到某个限制,我知道这一点)。
通过阅读,我了解了有关 pthread 工作原理的基础知识,并发现这篇文章与它非常相关:https://blog.madewithlove.be/post/thread-carefully/
我用一个基本的 symfony 项目做了一个示例案例来理解它:
[my_symf_project]\src\AppBundle\Controller 下的主控制器类:
class DefaultController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
// replace this example code with whatever you need
$tt = new TestThread('BOOOMSTICK');
$tt->start();
return $this->render('default/index.html.twig', [
'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..'),
]);
}
}
扩展Thread下的类:[my_symf_project]\src\AppBundle\DependencyInjection:
<?php
namespace AppBundle\DependencyInjection;
class TestThread extends \Thread {
public function __construct($text){
$this->text = $text;
}
public function run(){
$vendorAutoload= __DIR__.'/../../../vendor/autoload.php';
require_once $vendorAutoload;
require_once __DIR__.'/ClassOutsideThread.php';
$cot = new ClassOutsideThread(' RUN ' . ' ' . $this->text);
$cot->show();
}
}
?>
还有另一个类(在扩展线程的类之外)以及 [my_symf_project]\src\AppBundle\DependencyInjection:
<?php
namespace AppBundle\DependencyInjection;
class ClassOutsideThread {
public function __construct($text){
$this->text = $text;
}
public function show(){
echo $this->text;
}
}
?>
通过上面的代码,我设法在标准 symfony 空项目页面的顶部显示“RUN BOOOMSTICK”。我知道这是可能的,因为我添加了语句“require_once __DIR__.'/ClassOutsideThread.php';”在 run() 函数的开头。
现在我遇到了几个关于如何传递给子线程的问题:类和其他 symfony 上下文参数,通过 run() 函数。这是我想要得到的愿望清单:
- [my_symf_proj]\src\AppBundle 文件夹下的类文件:有没有一种快速的方法来加载该捆绑包下的所有类,例如在我的类 TestThread 中使用的有关“供应商”文件夹的自动加载(取自: Boostraping symfony 2 for pthread from command)?
- 我想在 run() 函数中使用 symfony 记录器。我试过:$GLOBALS['kernel']->getContainer()->get('logger'),但我在 [my_symf_proj] \var\logs\dev.log 中得到了一个很大的空白,所以我想知道如何通过子线程访问 $GLOBALS['kernel']->getContainer()?
- 我想在run() 函数中使用我的Doctrine 连接到数据库(对应于symfony 参数集的那个)。我怎样才能做到这一点? (我也试过 $GLOBALS['kernel']->getContainer()->get('dbal.connection'),但似乎没有成功。)
PS:我知道在特定的子线程情况下,使用 $GLOBALS['kernel']->getContainer() 也不是 symfony 的最佳实践,它似乎是一个方便的选择。
【问题讨论】:
标签: php multithreading pthreads symfony