Instantly share code, notes, and snippets.

View Laravel-Container.md

Laravel's Dependency Injection Container in Depth

Laravel has a powerful Inversion of Control (IoC) / Dependency Injection (DI) Container. Unfortunately the official documentation doesn't cover all of the available functionality, so I decided to experiment with it and document it for myself. The following is based on Laravel 5.4.26 - other versions may vary.

Introduction to Dependency Injection

I won't attempt to explain the principles behind DI / IoC here - if you're not familiar with them you might want to read What is Dependency Injection? by Fabien Potencier (creator of the Symfony framework).

Accessing the Container

View FizzBuzz.php
for ($i = 1; $i <= 100; $i++)
{
if($i % 3 == 0 && $i % 5 ==0){
echo "FizzBuzz<br />";
}
else if($i % 3 == 0){
echo "Fizz<br />";
}
else if($i % 5 == 0){
echo "Buzz<br />";
View Collection-Iterator-Aggregate.php
<?php
class Collection implements IteratorAggregate
{
/**
* The collection contents.
*
* @var array
*/
protected $items;
View artisan.php
<?php
require_once "vendor/autoload.php";
use Symfony\Component\Console\Application;
use Illuminate\Database\Console\Migrations;
use Pimple\Container;
$container = new Container();
$container['migration-table'] = 'migration';
View gist:affcb7546660a635953a438ad68ef71a
<?php
class Luhn
{
public function luhn_check($number)
{
$number = preg_replace('/\D/', '', $number);
$number_length = strlen($number);
View gist:ff5de140c757f98ccf57247edd1bd7fb
<?php
class ExpressionTest extends PHPUnit_Framework_TestCase
{
/** @test */
public function it_generates_Number()
{
$number = Luhn::make();
$this->generate('Luhn', $number);
View gist:b0d25cd6877a2d450f1497252c4b8e78
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
class PostsController extends Controller
{
public function index()
View gist:22f7e428a0924c20379efff3d6bf7067
<?php
use App\Post;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class BlogTest extends TestCase
{
use DatabaseTransactions;