1

I am trying to use illuminate library outside Laravel. By following this repo https://github.com/mattstauffer/IlluminateNonLaravel, I successfully use Eloquent model with my project. However, I setup the boot method, then it is not called.

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!
        });
    }
}

I can use model, but registering method is not called. I think the problem is I have not setup EventDispatcher correctly, but I don't know how to do it. Please help me!

Howard
  • 601
  • 1
  • 11
  • 15

1 Answers1

0

I have solved my problem. The key point is that do not create a new Encapsulator instance in every new Eloquent model. In https://github.com/mattstauffer/IlluminateNonLaravel, I extend from EncapsulatedEloquentBase for User model, so when I create two users and do somethings, they dispatcher is not same. This causes the problem.

So, the solution is let User extends Illuminate\Database\Eloquent\Model

<?php namespace App\Eloquent;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{

When somewhere to use it, just init Encapsulator once

Encapsulator::init();
User::create(['name' => 'John']);
Howard
  • 601
  • 1
  • 11
  • 15