6

i'm used to write a lot in codeigniter, where i try to place all logic code inside libraries instead of controllers.

The idea is a controller calls a library that calls a model to get data. So whatever is happening inside a library, can be called from multiple controllers easily, without rewriting code.

Now i'm baby stepping to laravel and i cannot find anything about custom libraries. I perfectly managed to call a model from a controller, but I want to have a controller calling a library and the library calling the model.

I'm not able to find libraries (not packages), do they exist in laravel ?

Thank you.

Simos Fasouliotis
  • 1,383
  • 2
  • 16
  • 35

3 Answers3

5

Laravel works with Services and Providers, you create your service and write a provider for it. Laravel Providers

Also you can have Services Directory which is served through Providers Directory.

anwerj
  • 2,386
  • 2
  • 17
  • 36
1
  1. First create Libraries directory inside app, then just create simple classes inside Libraries with functions which will call the models. remember to write

    namespace App\Libraries

    in every library you create.

  2. then in composer.json add this line "App\\Libraries\\": "src" as the result your composer.json will become something like this

     `"autoload":{
         "psr-4": {
          "App\\": "app/",
          "App\\Libraries\\": "src",
    
     },}`
    
  3. simply in your controller instantiate the library you want and use it's functions.

Wasiq Ahmadzai
  • 161
  • 1
  • 7
0

You mean using namespacing ? if you mean that take look about this post , its explain how create package http://culttt.com/2013/06/24/creating-a-laravel-4-package/

Issam Ben Ameur
  • 249
  • 2
  • 12
  • I dont know for sure, i'm just trying to understand if making libraries is legit in laravel, or else where should i write my code logic. – Simos Fasouliotis Aug 07 '17 at 17:33
  • Yes you can do it , first should add this into your composer.jason "autoload": { "classmap": [ // -- "app/lib" ] } then run composer dump-autoload then add your library to provider – Issam Ben Ameur Aug 07 '17 at 17:38
  • More detail here : http://culttt.com/2013/07/08/creating-flexible-controllers-in-laravel-4-using-repositories/ – Issam Ben Ameur Aug 07 '17 at 17:39
  • library is like creating repository in your case . When you finish you can call your library anywhere and better than calling from anywhere repository pattern give you a strong architecture to maintain your app – Issam Ben Ameur Aug 07 '17 at 17:41