Taking advantage of spl_autoload_register
I had to make a small modification in the codeigniter index.php file
Codeigniter index.php
function load_traits($traits)
{
$traits_found = [];
$traitsBasePath = APPPATH .'traits';
find_trait($traitsBasePath, $traits, $traits_found);
foreach ($traits_found as $found)
include_once $found;
}
function find_trait($dir, $searchForTrait, &$found)
{
if(is_string($searchForTrait))
{
$dirHandle = opendir($dir);
if($dirHandle !== FALSE)
{
while (false !== ($entry = readdir($dirHandle)))
if($entry != '.' && $entry != '..')
if(is_dir($dir. '/' .$entry))
find_trait($dir. DIRECTORY_SEPARATOR .$entry, $searchForTrait, $found);
else
if(strpos($dir. DIRECTORY_SEPARATOR .$entry,
str_replace("/", DIRECTORY_SEPARATOR, $searchForTrait . '.php')) !== FALSE)
array_push($found, $dir. DIRECTORY_SEPARATOR .$entry);
}
else
die("Traits directory does not exists");
}
else if(is_array($searchForTrait))
{
$dirHandle = opendir($dir);
if($dirHandle !== FALSE)
{
while (false !== ($entry = readdir($dirHandle)))
if($entry != '.' && $entry != '..')
foreach ($searchForTrait as $sTrait) {
if(is_dir($dir. '/' .$entry))
find_trait($dir. DIRECTORY_SEPARATOR .$entry, $sTrait, $found);
else
if(strpos($dir. DIRECTORY_SEPARATOR .$entry,
str_replace("/",
DIRECTORY_SEPARATOR,
$sTrait . '.php')) !== FALSE)
array_push($found, $dir. DIRECTORY_SEPARATOR .$entry);
}
}
else
die("Traits directory does not exists");
}
else
die("Parameter must be string or array");
}
spl_autoload_register(function($traitname) {
load_traits($traitname);
});
Having saying that, you must to create a traits
folder into codeigniter application
directory and create your traits there.
How do i use this?
In any controller you just use it as follows
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Store extends CI_Controller {
use test_trait;
}
When use test_trait
the file test_trait.php
will be searched in traits directory. If the file is found will be automatically included