Creating and using Libraries in Laravel 5.1

Asked

Viewed 788 times

2

I am new to Laravel 5.1 (I come from Codeigniter) and I have my own libraries that I would like to implement in it. In Codeigniter, we have the folder libraries where I can play all my libraries there and if 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 controllers.

1 answer

2

Using Laravel or any other modern framework you will notice many differences with Codeigniter. He "stopped" in time and did not follow the novelties that have emerged over the years in the PHP community.

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

To use your old codes, you need to modify all of them to eliminate dependencies with Codeigniter and apply Namespaces in their classes so that they are compatible with PSR-4.

The directory you can do this can be anyone, as long as it is set in your composer.json:

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

Directory structure

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

To use an own class called View.php you can include it in use shortly after the namespace and import via Type Hint from Laravel 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();
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.