Namespace in PHP CodeIgniter Framework

Viewed 40429

Does CodeIgniter support Namespace?

5 Answers

Just a simple psr-4 autoloading and you are done.

In the config/config.php load composer using

$config['composer_autoload'] = FCPATH.'vendor/autoload.php';

In the root directory run composer install In the generated composer.json add following lines for psr4 autoloading.

    "autoload": {
        "psr-4": {
            "App\\": "application/"
        }
    },  

App would be your namespace in this case.

Example: suppose you have a class Service in libraries folder. You can namespace it with:

<?php
namespace App\libraries;

class Service{
}

Use it in Welcome controller class:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use App\libraries\Service;
class Welcome extends CI_Controller {
}

You could check this out: yidas/codeigniter-psr4-autoload

The lib defines app as CI application root so that every classes in application could be loaded with PSR-4 namespace:

\app\libraries\MemberService::auth();
\app\helpers\ArrayHelper::indexBy($input);
\app\widgets\StatWidget::run();
class Blog_model extends app\core\BaseModel {}
class Car_model implements app\contracts\CarInterface {}

Sample code for defining a class:

<?php
namespace app\helpers;
class ArrayHelper
{
    public static function indexBy($input) {}
}

https://github.com/yidas/codeigniter-psr4-autoload

add the line below in a class that you want to use goutte`

require __DIR__ . "/../../../vendor/autoload.php";

and in absolute path of your project run :`composer

require fabpot/goutte

to add goutte in your package.json file. now all things should work well.`

Related