Skip to content

Instantly share code, notes, and snippets.

@gregarious-repo
Created April 27, 2014 18:24
Show Gist options
  • Save gregarious-repo/11352198 to your computer and use it in GitHub Desktop.
Save gregarious-repo/11352198 to your computer and use it in GitHub Desktop.
Laravel multi vendor IoC API binding
<?php
// Api filters.php
Route::filter('controller', function ($route, $request) {
$client = ucfirst($route->getParameter('client'));
$resource = ucfirst($route->getName());
//Register service provider on fly for rest of the dispatch loop.
//If something will go wrong with any client we don't affect any other clients
// Example:: Acme\Company\CompanyServiceProvider
$servicePovider = sprintf('Acme\%s\%sServiceProvider', $client, $client );
App::register( $servicePovider );
//Model
$model = sprintf('Acme\%s\Model\%s', $client, ucwords(camel_case($resource) ));
try {
//Check if Model name in singular exists
if ( class_exists( str_singular( $model ) )) $bind = $model;
else throw new Illuminate\Database\Eloquent\ModelNotFoundException( $model );
} catch ( ModelNotFoundException $e ) {
App::abort(404);
}
//Here we are binding Client model into example RepositoryInterface for rest of the dispatch loop.
App::bind('Acme\Api\Repository\RepositoryInterface', $bind );
});
// Api routes.php
Route::group(array('before' => 'controller'), function () {
Route::group(array('as' => 'category'), function(){
Route::get('/api/{client}/category.{type}', 'Acme\Api\Controller\CategoryController@index', 'type');
Route::get('/api/{client}/category/{id}.{type}', 'Acme\Api\Controller\CategoryController@show', 'id', 'type');
});
Route::group(array('as' => 'product'), function(){
Route::get('/api/{client}/product.{type}', 'Acme\Api\Controller\ProductController@index', 'type');
Route::get('/api/{client}/product/{id}.{type}', 'Acme\Api\Controller\ProductController@show', 'id', 'type');
});
});
// Api Controllers
// CategoryController.php
use Acme\Api\Repository\RepositoryInterface AS Category;
class CategoryController extends \Controller
{
protected $category;
public function __construct(Category $category)
{
$this->category = $category;
}
}
// ProductController.php
use Acme\Api\Repository\RepositoryInterface as Product;
class ProductsController extends \Controller
{
protected $product;
public function __construct(Product $product)
{
$this->product = $product;
}
}
// Client Models
// Category.php
class Category extends \Eloquent implements RepositoryInterface
{
}
// Product.php
class Product extends \Eloquent implements RepositoryInterface
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment