Skip to content

Instantly share code, notes, and snippets.

@hannesvdvreken
hannesvdvreken / MazeCommand.php
Created April 18, 2014 22:24
LaravelPHP artisan command to search the apibunny maze
<?php
use Guzzle\Http\Client;
use Guzzle\Http\Exception\BadResponseException;
use Illuminate\Console\Command;
use Illuminate\Foundation\Application;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class MazeCommand extends Command
@hannesvdvreken
hannesvdvreken / blogpost-ioc.md
Last active August 29, 2015 14:12
Blog post on IoC containers

IoC containers

At work I'm currently modernising a legacy project without composer into an application with less code and thus less bugs. The first composer package I required was an application container to add Dependency Injection to the project. The container I used is called orno/di.

I bootstrapped the container in the index file. After that I registered some basic stuff to it like an object of the Symfony Request class, a Monolog logger with rotating log files, ... Finally I was able to adapt the existing old router to resolve the controllers and their dependencies from the IoC container.

In a couple of hours I had enabled the project to adopt and inject composer loaded classes within minutes.

Auto resolving

$app->bind('\Vendor\Chat\Client', function ($app) {
$config = $app['config'];
$guzzle = $app->make('Guzzle\Http\Client');
$baseUrl = $config->get('services.chat.base_url');
$token = $config->get('services.chat.token');
return new Client($guzzle, $baseUrl, $token);
});
$app->bind('\Vendor\Chat\Client', function (GuzzleHttp\Client $client, Repository $config) {
$baseUrl = $config->get('services.chat.base_url');
$token = $config->get('services.chat.token');
return new Client($guzzle, $baseUrl, $token);
});
$posts = Cache::remember('posts', $minutes, function (PostsRepository $repo) {
return $repo->all();
});
Schema::table('users', function (Blueprint $table, AddressConverter $converter) {
...
});
$posts = Cache::remember('posts', $minutes, App::wrap(function (PostsRepository $repo) {
return $repo->all();
}));
set_exception_handler(App::wrap(function (Whoops\Run) {...}));
$callables = [
'Class::staticMethodName',
'\Namespace\method_name',
[$object, 'methodName'],
function (\Vendor\Dependency $object) {...},
];
// This will work for every item in the array
foreach ($callables as $callable) {
call_user_func($callable);
$app->bind('\Vendor\Contracts\Client', '\Vendor\Client');