Skip to content

Instantly share code, notes, and snippets.

@ziadoz
Last active November 28, 2018 14:40
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save ziadoz/5541858 to your computer and use it in GitHub Desktop.
Save ziadoz/5541858 to your computer and use it in GitHub Desktop.
Laravel 4 Eloquent ORM Standalone (Observers, Query Logging).
<?php
class Post
{
protected $table = 'posts';
/**
* You can define your own custom boot method.
*
* @return void
**/
public static function boot()
{
parent::boot();
static::creating(function($post) {
echo 'Creating';
});
}
/**
* You can access the database connection in a static model method with the resolver.
*
* @return void
**/
static public function doSomething()
{
$db = static::resolveConnection();
}
}
class PostObserver
{
public function creating($post)
{
echo 'Creating';
}
public function created($post)
{
echo 'Created';
}
public function updating($post)
{
echo 'Updating';
}
public function updated($post)
{
echo 'Updated';
}
public function deleting($post)
{
echo 'Deleting';
}
public function deleted($post)
{
echo 'Deleted';
}
public function saving($post)
{
echo 'Saving';
}
public function saved($post)
{
echo 'Saved';
}
}
// Setup Capsule.
// See: https://github.com/illuminate/database
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule;
$capsule->addConnection(array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
));
// Setup the Eloquent ORM... (optional).
$capsule->bootEloquent();
// Set the event dispatcher used by Eloquent models... (optional).
use Illuminate\Events\Dispatcher;
$capsule->setEventDispatcher(new Dispatcher);
// Set the cache manager instance used by connections... (optionaL).
use Illuminate\Support\Container;
use Illuminate\Cache\CacheManager;
$cache = new CacheManager(new Container);
$cache->driver('apc');
$capsule->setCacheManager($cache);
// Make this Capsule instance available globally via static methods... (optional).
$capsule->setAsGlobal();
// Observe / Forget Post events.
// See: https://github.com/laravel/framework/issues/1339
$observer = new PostObserver;
$capsule->getContainer()->instance('PostObserver', $observer);
Post::observe($observer);
Post::forget('saved');
// Create / Update / Delete a Post model.
$post = new Post;
$post->title = 'Hello, World!';
$post->save();
$post->delete();
// Fill a Post model.
$post = new Post;
$post->fill(array('title' => 'Hello, World!'));
// Get the query log.
$queries = $capsule->connection()->getQueryLog();
@ingro
Copy link

ingro commented May 13, 2013

Interesting approach! Do you think it will be possible to implement the EloquentEventSubscriver in a way that it is included by default in each BaseModel, without the need to create one for each Model?

@ziadoz
Copy link
Author

ziadoz commented May 14, 2013

Eloquent has a static method called boot() that you can use to setup any events you want to be permanently attached to a model. I've added some example code that shows how you can use it.

@ingro
Copy link

ingro commented May 15, 2013

Thank you, good catch! Anyway I wanted to implement this in a way that there are defaults methods that get called as the events fire, like that:

static::creating(function($post) {
    $post->onCreating();
});

and include that in the BaseModel Class so these are available for all my models.

Do you think it's a valid approach?

@ziadoz
Copy link
Author

ziadoz commented May 15, 2013

If you need to do something every time a model event is fired then it probably makes sense to put the code inside the model class itself. If it's something separate (E.g. a registration or password reset email), then I would use an event subscriber class and register it where it's needed.

Edit: Eloquent has built in observers now, and I've put a pull request in to allow the default connection to be retrieved statically, so the BaseModel class probably won't be needed soon enough.

@zofe
Copy link

zofe commented Nov 15, 2013

nice, what about paginating Eloquent results stand-alone ?
I'm trying to use Illuminate\Pagination but it need Environment, Views, and I could not make it work "stand-alone".

So basically I use:

    $post->skip(offset)->take(limit)->get();

How to make it work with:

$post->paginate(limit);
...
$post->paginate(limit)->links(); 

?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment