Codeigniter 4 – Creating a Library with Example
Creating a Library
- Create a new file in the app/Libraries directory.
- Extend the CodeIgniter\Libraries\BaseLibrary class.
Example:
namespace App\Libraries;
use CodeIgniter\Libraries\BaseLibrary;
class MyLibrary extends BaseLibrary
{
public function doSomething()
{
// Library code here
}
}
Loading a Library
- Use the library() method to load a library.
Example:
$myLibrary = library('MyLibrary');
Using a Library
- Call methods on the library object.
Example:
$myLibrary->doSomething();
Creating a Library with Dependencies
- Use the __construct() method to inject dependencies.
Example:
namespace App\Libraries;
use CodeIgniter\Libraries\BaseLibrary;
use CodeIgniter\Database\BaseConnection;
class MyLibrary extends BaseLibrary
{
protected $db;
public function __construct(BaseConnection $db)
{
$this->db = $db;
}
public function doSomething()
{
// Use the database connection
$this->db->query('SELECT * FROM users');
}
}
Creating a Library with Configuration
- Use the __construct() method to inject configuration.
Example:
namespace App\Libraries;
use CodeIgniter\Libraries\BaseLibrary;
use CodeIgniter\Config\BaseConfig;
class MyLibrary extends BaseLibrary
{
protected $config;
public function __construct(BaseConfig $config)
{
$this->config = $config;
}
public function doSomething()
{
// Use the configuration
echo $this->config->get('app.name');
}
}
I hope this helps! Let me know if you have any further questions or need more information.
Note: Libraries in CodeIgniter 4 provide a way to organize and reuse code. They can be used to perform specific tasks, interact with external services, or provide utility functions.