Table des matières

Bibliothèques

  1. Bibliothèques

Une bibliothèque est une classe php disposant de multiples fonctionnalités.

Création d'une bibliothèque

  • Une bibliothèque est un fichier contenant une classe dont le nom commence par une majuscule.
  • Le nom du fichier doit être le même que celui de la classe, mais en minuscule.
  • Le fichier doit être enregistré dans le dossier application/libraries/

Nous allons créer une bibliothèque permettant de gérer une collection d'objets, à partir d'un tableau.
Créer le fichier collection.php dans application/libraries/ :

|h application/libraries/collection.php
<?php
class Collection {
	private $items;
	public function __construct() {
		$this->items=array();
	}
	public function add($anObject){
		$this->items[]=$anObject;
	}
	public function indexOf($anObject) {
		return array_search($anObject,$this->items);
	}
	public function delete($index){
		if(array_key_exists($index, $this->items)){
			unset($this->items[$index]);
			$this->items=array_values($this->items);
		}
	}
	public function getItem($index){
		return $this->items[$index];
	}
	public function size(){
		return sizeof($this->items);
	}
	public function getItems(){
		return $this->items;
	}
}
?>

Utilisation d'une bibliothèque

La bibliothèque doit être chargée :

$autoload['libraries'] = array('database','session','collection');
$this->load->library('collection');
|h controllers/test.php
<?php
class Test extends CI_Controller{
	function __construct(){
		parent::__construct();
	}
	public function testCollection(){
		$this->collection->add("1 chaîne");
		$this->collection->add("2 chaînes");
		foreach ($this->collection->getItems() as $value)
			echo($value."<br>");
 
	}
}
?>

Aller à l'adresse http://localhost/testPhp/test/testCollection/ :

  • Le premier appel de $this->collection instancie une nouvelle collection
  • $this->load appelé précédemment correspond à l'utilisation de la librairie load