我想在Laravel外面使用illuminate library。通过遵循此回购https://github.com/mattstauffer/IlluminateNonLaravel,我成功地将Eloquent模型与我的项目一起使用。但是,我设置了启动方法,然后没有调用它。
Encapsulator.php
<?php namespace App\Eloquent;
use Illuminate\Container\Container;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Events\Dispatcher;
class Encapsulator
{
private static $conn;
private function __construct() {}
static public function init()
{
if (is_null(self::$conn))
{
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'mysql',
'host' => HOSTNAME,
'database' => DATABASE,
'username' => USERNAME,
'password' => PASSWORD,
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => PREFIX,
]);
$capsule->setEventDispatcher(new Dispatcher(new Container));
$capsule->setAsGlobal();
$capsule->bootEloquent();
}
}
}
EncapsulatedEloquentBase.php
<?php namespace App\Eloquent;
use Illuminate\Database\Eloquent\Model as Eloquent;
abstract class EncapsulatedEloquentBase extends Eloquent
{
public function __construct(array $attributes = array())
{
Encapsulator::init();
parent::__construct($attributes);
}
}
user.php的
<?php namespace App\Eloquent;
class User extends EncapsulatedEloquentBase
{
protected static function boot() {
parent::boot();
echo 'hey boot!!'; // called!
static::creating(function($node) {
echo 'hey creating!!'; // never called!
});
}
}
我可以使用模型,但不调用注册方法。我认为问题是我没有正确设置EventDispatcher,但我不知道该怎么做。请帮帮我!
答案 0 :(得分:0)
我已经解决了我的问题。关键是不要在每个新的Eloquent模型中创建一个新的Encapsulator实例。 在https://github.com/mattstauffer/IlluminateNonLaravel中,我从用户模型的EncapsulatedEloquentBase扩展,因此当我创建两个用户并执行某些操作时,他们的调度程序不同。这导致了问题。
因此,解决方案是让用户扩展Illuminate \ Database \ Eloquent \ Model
<?php namespace App\Eloquent;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
当某处使用它时,只需初始化封装器
Encapsulator::init();
User::create(['name' => 'John']);