Creating and using Libraries in Laravel 5.1

1

I'm new to Laravel 5.1 (I come from CodeIgniter) and I have libraries of my own that I'd like to implement in it. In CodeIgniter, we have the folder libraries where I can play all my libraries there and if in case I need the same just need to load them using a $this->load->library('minha_biblioteca');

How can I use this same library and its methods within Laravel? Where should I put it and how to call it in my drivers.

    
asked by anonymous 30.12.2015 / 12:05

1 answer

1

When using Laravel or any other modern Framework you will notice many differences with Codeigniter. It "stopped" in time and did not keep up with the news that has come up over the years in the PHP community (Yes, it simply stopped for years).

Currently, for external libraries, the codes are loaded from PHP Autoload , following a pattern of directory structure ( PSR-4 or PSR-0 ) for automatic loading. This is all done by Composer and Laravel already uses it .

To use your old code, you need to modify all of them to eliminate dependencies with Codeigniter, to apply Namespaces to your classes in a way that supports PSR-4.

The directory you can do this can be any one, as long as it is defined in composer.json:

},
"autoload": {
    "psr-4": {
        "App\": "app/",
        "MinhaBiblioteca\": "src/"
    }
},

Directory structure

src
 |_ Utils
     |_ View.php
     |_ ScripView.php

To use View.php in any class (including Controllers):

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use MinhaBiblioteca\Utils\View;

class MeuController extends Controller
{

    public function getIndex()
    {
        $v = new View();
    }

}
    
30.12.2015 / 13:53