Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autoload 'libraries' in laravel 4?

I've created a library folder in app folder to add my app libraries. I've updated app config file and composer.json to autoload that folder, but when I run the command composer dump-autoload I get the next error:

{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'App\\Libraries\\Search\\SearchServiceProvider' not found","file":"D:\\Users\\Miguel Borges\\Documents\\Trabalhos\\Tese\\portal\\bootstrap\\compiled.php","line":4130}}PHP Fatal error: Class 'App\Libraries\Search\SearchServiceProvider' not found in D:\Users\Miguel Borges\Documents\Trabalhos\Tese\portal\bootstrap\compiled.php on line 4130 [Finished in 1.1s with exit code 255]

My app folder tree:

app
| ...
+ libraries
| + search
| | - Search.php
| | - SearchFacade.php
| | - SearchServiceProvider.php
| + lib2
| | - ...
| + lib3
| | - ...
| | - Theme.php
| - ...
- filters.php
- routes.php

SearchServiceProvider.php

namespace App\Libraries\Search;

use Illuminate\Support\ServiceProvider;

class SearchServiceProvider extends ServiceProvider {

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['search'] = $this->app->share(function($app)
        {
            return new Search;
        });
    }

}

composer.json

    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/libraries",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ]
        // ,
  //       "psr-0": {
  //           "app": "app/libraries"
  //       }
    },

Basically, I need to autoload all the libraries within the 'libraries' folder.

like image 501
Miguel Borges Avatar asked Jul 11 '13 04:07

Miguel Borges


1 Answers

You should create a top-level namespace for your application.

Then put all libraries you code under that namespace. Note: Any third-party libraries should (hopefully) be installed via Composer and therefore have its own namespace/autoloading setup.

Your directory structure would then be:

libraries
    Myapp
        Search (note directory is capitalized)
            Search.php
            SearchFacade.php
            SearchServiceProvider.php
        AnotherLib

Then your classes will follow that namespace:

File: Myapp/Search/Search.php:

<?php namespace Myapp\Search;

class Search { ... }

And finally, your autoloading setup:

"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/libraries",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php"
    ]
    ,
    "psr-0": {
         "Myapp": "app/libraries"
    }
},
like image 168
fideloper Avatar answered Nov 13 '22 18:11

fideloper