Skip to content

Instantly share code, notes, and snippets.

@DuffleOne
Last active August 29, 2015 14:21
Show Gist options
  • Save DuffleOne/990efa2c46136283ce7e to your computer and use it in GitHub Desktop.
Save DuffleOne/990efa2c46136283ce7e to your computer and use it in GitHub Desktop.
Demo for a Redditor
<?php
// Imagine this extends Eloquent Model
class Article {
protected $image;
protected $api;
// You don't inject the Image or the API
// But you do build them up inside the Model.
public function __construct()
{
$this->image = new Image($this);
$this->api = new API($this);
// On creation, do stuff.
$this->bootUp();
}
private function bootUp()
{
$this->image->optimize();
$this->api->inform();
}
// This is where this idea fails:
// You NEED to call this method manually when deleteing the Article.
// If you use any other type of delete, then this won't be called.
// Look into Laravel Model observers and bind this function to `deleted`.
public function bootDown()
{
$this->image->unlink();
}
}
class Image {
protected $article;
public function __construct(Article $article)
{
$this->article = $article;
}
public function optimize()
{
// do some sort of optimize action;
echo("Optimzed Image\n");
return $this;
}
public function unlink()
{
// unlink stuff here
// can even access article attributes on $this->article->attribute;
echo("Unlinked Image\n");
return $this;
}
}
class API {
protected $article;
public function __construct(Article $article)
{
$this->article = $article;
}
public function inform()
{
// do the inform() stuff
echo("Informed API\n");
return $this;
}
}
// Build the Article.
// $image->optimize() and $api->inform() are auto called.
$article = new Article();
// Delete the Article
$article->bootDown();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment