我必须在 Yii 1.1 应用程序中解析一个巨大的 csv 文件。每一行都必须经过验证并保存到数据库中。我决定使用多线程来完成这项任务。
因此,这是我在控制器操作中的代码:
public function parseData($) {
$this->content = explode("'n", $this->content);
$thread_1 = new DatalogThread(array_slice($this->content, 0, 7000));
$thread_2 = new DatalogThread(array_slice($this->content, 7001));
$thread_1->start();
$thread_2->start();
}
还有线程(我把它放在模型文件夹中):
class DatalogThread extends Thread {
public $content;
public function __construct($content) {
$this->content = $content;
}
public function run() {
foreach ($this->content as $value) {
$row = str_getcsv($value);
$datalog = new Datalog($row);
$datalog->save();
}
}
}
问题是线程无法访问模型文件:
致命错误:在 C:''xampp...''protected''models''DatalogThread.php 中找不到类"Datalog
我尝试了Yii::autoload("Datalog"),但得到以下错误:
致命错误:无法访问 402 行 ...''YiiMain''framework''YiiBase.php 中的属性 Yii::$_coreClasses
Yii 使用了很多静态,这不是多线程的最佳代码。
你要做的是初始化不知道 Yii 的线程并重新加载它,我不使用 Yii,但这里有一些工作可以让你知道该怎么做:
<?php
define ("MY_YII_PATH", "/usr/src/yii/framework/yii.php");
include (MY_YII_PATH);
class YiiThread extends Thread {
public $path;
public $config;
public function __construct($path, $config = array()) {
$this->path = $path;
$this->config = $config;
}
public function run() {
include (
$this->path);
/* create sub application here */
}
}
$t = new YiiThread(MY_YII_PATH);
$t->start(PTHREADS_INHERIT_NONE);
?>
这会更好地工作...我应该认为你想要 yii 在你的线程中调用控制台应用程序,因为你不希望它试图发送任何标头或类似的东西......
这应该让你开始...