From fb59727e5e47aef6c0fc801fa3c82f429874d6f2 Mon Sep 17 00:00:00 2001
From: grandj161u <matheo.grandjean8@etu.univ-lorraine.fr>
Date: Sat, 8 Mar 2025 19:39:03 +0100
Subject: [PATCH] =?UTF-8?q?passage=20en=20slim=204=20et=20autres=20framewo?=
 =?UTF-8?q?rks=20ou=20bd=20en=20derni=C3=A8res=20versions?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 composer.json               |   4 +-
 controller/Search.php       |  76 +++++----
 controller/addItem.php      | 176 +++++++++----------
 controller/getCategorie.php |  46 +++--
 controller/index.php        |  39 +++--
 controller/item.php         | 137 +++++++++------
 index.php                   | 328 ++++++++++++++++++++++--------------
 7 files changed, 472 insertions(+), 334 deletions(-)

diff --git a/composer.json b/composer.json
index e905808..5f8093b 100644
--- a/composer.json
+++ b/composer.json
@@ -9,7 +9,9 @@
         "illuminate/container": "^12.0.1",
         "illuminate/support": "^12.0.1",
         "twig/twig": "^3.0",
-        "nesbot/carbon": "^3.8.6"
+        "nesbot/carbon": "^3.8.6",
+        "slim/twig-view": "^3.4",
+        "php-di/php-di": "^7.0"
     },
     "autoload":{
         "psr-0":{
diff --git a/controller/Search.php b/controller/Search.php
index fc0b01e..db9ef04 100644
--- a/controller/Search.php
+++ b/controller/Search.php
@@ -5,75 +5,89 @@ namespace controller;
 use model\Annonce;
 use model\Categorie;
 
-class Search {
+class Search
+{
 
-    function show($twig, $menu, $chemin, $cat) {
-        $template = $twig->loadTemplate("search.html.twig");
+    function show($twig, $menu, $chemin, $cat, $response)
+    {
         $menu = array(
-            array('href' => $chemin,
-                'text' => 'Acceuil'),
-            array('href' => $chemin."/search",
-                'text' => "Recherche")
+            array(
+                'href' => $chemin,
+                'text' => 'Acceuil'
+            ),
+            array(
+                'href' => $chemin . "/search",
+                'text' => "Recherche"
+            )
         );
-        echo $template->render(array("breadcrumb" => $menu, "chemin" => $chemin, "categories" => $cat));
+
+        return $twig->render($response, "search.html.twig", [
+            "breadcrumb" => $menu,
+            "chemin" => $chemin,
+            "categories" => $cat
+        ]);
     }
 
-    function research($array, $twig, $menu, $chemin, $cat) {
-        $template = $twig->loadTemplate("index.html.twig");
+    function research($array, $twig, $menu, $chemin, $cat, $response)
+    {
         $menu = array(
-            array('href' => $chemin,
-                'text' => 'Acceuil'),
-            array('href' => $chemin."/search",
-                'text' => "Résultats de la recherche")
+            array(
+                'href' => $chemin,
+                'text' => 'Acceuil'
+            ),
+            array(
+                'href' => $chemin . "/search",
+                'text' => "Résultats de la recherche"
+            )
         );
 
         $nospace_mc = str_replace(' ', '', $array['motclef']);
         $nospace_cp = str_replace(' ', '', $array['codepostal']);
 
-
         $query = Annonce::select();
 
-        if( ($nospace_mc === "") &&
+        if (($nospace_mc === "") &&
             ($nospace_cp === "") &&
             (($array['categorie'] === "Toutes catégories" || $array['categorie'] === "-----")) &&
             ($array['prix-min'] === "Min") &&
-            ( ($array['prix-max'] === "Max") || ($array['prix-max'] === "nolimit") ) ) {
+            (($array['prix-max'] === "Max") || ($array['prix-max'] === "nolimit"))
+        ) {
             $annonce = Annonce::all();
-
         } else {
             // A REFAIRE SEPARER LES TRUCS
-            if( ($nospace_mc !== "") ) {
-                $query->where('description', 'like', '%'.$array['motclef'].'%');
+            if (($nospace_mc !== "")) {
+                $query->where('description', 'like', '%' . $array['motclef'] . '%');
             }
 
-            if( ($nospace_cp !== "") ) {
+            if (($nospace_cp !== "")) {
                 $query->where('ville', '=', $array['codepostal']);
             }
 
-            if ( ($array['categorie'] !== "Toutes catégories" && $array['categorie'] !== "-----") ) {
+            if (($array['categorie'] !== "Toutes catégories" && $array['categorie'] !== "-----")) {
                 $categ = Categorie::select('id_categorie')->where('id_categorie', '=', $array['categorie'])->first()->id_categorie;
                 $query->where('id_categorie', '=', $categ);
             }
 
-            if ( $array['prix-min'] !== "Min" && $array['prix-max'] !== "Max") {
-                if($array['prix-max'] !== "nolimit") {
+            if ($array['prix-min'] !== "Min" && $array['prix-max'] !== "Max") {
+                if ($array['prix-max'] !== "nolimit") {
                     $query->whereBetween('prix', array($array['prix-min'], $array['prix-max']));
                 } else {
                     $query->where('prix', '>=', $array['prix-min']);
                 }
-            } elseif ( $array['prix-max'] !== "Max" && $array['prix-max'] !== "nolimit") {
+            } elseif ($array['prix-max'] !== "Max" && $array['prix-max'] !== "nolimit") {
                 $query->where('prix', '<=', $array['prix-max']);
-            } elseif ( $array['prix-min'] !== "Min" ) {
+            } elseif ($array['prix-min'] !== "Min") {
                 $query->where('prix', '>=', $array['prix-min']);
             }
 
             $annonce = $query->get();
         }
 
-        echo $template->render(array("breadcrumb" => $menu, "chemin" => $chemin, "annonces" => $annonce, "categories" => $cat));
-
+        return $twig->render($response, "index.html.twig", [
+            "breadcrumb" => $menu,
+            "chemin" => $chemin,
+            "annonces" => $annonce,
+            "categories" => $cat
+        ]);
     }
-
 }
-
-?>
\ No newline at end of file
diff --git a/controller/addItem.php b/controller/addItem.php
index deb5bed..e63fc55 100755
--- a/controller/addItem.php
+++ b/controller/addItem.php
@@ -5,26 +5,27 @@ namespace controller;
 use model\Annonce;
 use model\Annonceur;
 
-class addItem{
-
-    function addItemView($twig, $menu, $chemin, $cat, $dpt){
-
-        $template = $twig->loadTemplate("add.html.twig");
-        echo $template->render(array(
-                                    "breadcrumb" => $menu,
-                                    "chemin" => $chemin,
-                                    "categories" => $cat,
-                                    "departements" => $dpt)
-                                );
-
+class addItem
+{
+
+    function addItemView($twig, $menu, $chemin, $cat, $dpt, $response)
+    {
+        return $twig->render($response, "add.html.twig", [
+            "breadcrumb" => $menu,
+            "chemin" => $chemin,
+            "categories" => $cat,
+            "departements" => $dpt
+        ]);
     }
 
-    function addNewItem($twig, $menu, $chemin, $allPostVars){
+    function addNewItem($twig, $menu, $chemin, $allPostVars, $response)
+    {
 
         date_default_timezone_set('Europe/Paris');
 
-        function isEmail($email) {
-            return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
+        function isEmail($email)
+        {
+            return (preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
         }
 
         /*
@@ -56,87 +57,87 @@ class addItem{
         $errors['priceAdvertiser'] = '';
         $errors['passwordAdvertiser'] = '';
 
-//        $fileInfos = $_FILES["fichier"];
-//        $fileName = $fileInfos['name'];
-//        $type_mime = $fileInfos['type'];
-//        $taille = $fileInfos['size'];
-//        $fichier_temporaire = $fileInfos['tmp_name'];
-//        $code_erreur = $fileInfos['error'];
-
-
-//        switch ($code_erreur){
-//            case UPLOAD_ERR_OK :
-//                $destination = "$chemin/upload/$fileName";
-//
-//                if (move_uploaded_file($fichier_temporaire, $destination)){
-//                    $message  = "Transfert terminé - Fichier = $nom - ";
-//                    $message .= "Taille = $taille octets - ";
-//                    $message .= "Type MIME = $type_mime";
-//                } else {
-//                   $message = "Problème de copie sur le serveur";
-//                }
-//                break;
-//            case UPLOAD_ERR_NO_FILE :
-//                $message = "Pas de fichier saisi";
-//                break;
-//            case UPLOAD_ERR_INI_SIZE :
-//                $message  = "Fichier '$fileName' non transféré ";
-//                $message .= ' (taille > upload_max_filesize.';
-//                break;
-//            case UPLOAD_ERR_FORM_SIZE :
-//                $message  = "Fichier '$fileName' non transféré ";
-//                $message .= ' (taille > MAX_FILE_SIZE.';
-//                break;
-//            case UPLOAD_ERR_PARTIAL :
-//                $message  = "Fichier '$fileName' non transféré ";
-//                $message .= ' (problème lors du transfert';
-//                break;
-//            case UPLOAD_ERR_NO_TMP_DIR :
-//                $message  = "Fichier '$fileName' non transféré ";
-//                $message .= ' (pas de répertoire temporaire).';
-//                break;
-//            case UPLOAD_ERR_CANT_WRITE :
-//                $message  = "Fichier '$fileName' non transféré ";
-//                $message .= ' (erreur lors de l\'écriture du fichier sur disque).';
-//                break;
-//            case UPLOAD_ERR_EXTENSION :
-//                $message  = "Fichier '$fileName' non transféré ";
-//                $message .= ' (transfert stoppé par l\'extension).';
-//                break;
-//            default :
-//                $message  = "Fichier '$fileName' non transféré ";
-//                $message .= ' (erreur inconnue : $code_erreur';
-//        }
+        //        $fileInfos = $_FILES["fichier"];
+        //        $fileName = $fileInfos['name'];
+        //        $type_mime = $fileInfos['type'];
+        //        $taille = $fileInfos['size'];
+        //        $fichier_temporaire = $fileInfos['tmp_name'];
+        //        $code_erreur = $fileInfos['error'];
+
+
+        //        switch ($code_erreur){
+        //            case UPLOAD_ERR_OK :
+        //                $destination = "$chemin/upload/$fileName";
+        //
+        //                if (move_uploaded_file($fichier_temporaire, $destination)){
+        //                    $message  = "Transfert terminé - Fichier = $nom - ";
+        //                    $message .= "Taille = $taille octets - ";
+        //                    $message .= "Type MIME = $type_mime";
+        //                } else {
+        //                   $message = "Problème de copie sur le serveur";
+        //                }
+        //                break;
+        //            case UPLOAD_ERR_NO_FILE :
+        //                $message = "Pas de fichier saisi";
+        //                break;
+        //            case UPLOAD_ERR_INI_SIZE :
+        //                $message  = "Fichier '$fileName' non transféré ";
+        //                $message .= ' (taille > upload_max_filesize.';
+        //                break;
+        //            case UPLOAD_ERR_FORM_SIZE :
+        //                $message  = "Fichier '$fileName' non transféré ";
+        //                $message .= ' (taille > MAX_FILE_SIZE.';
+        //                break;
+        //            case UPLOAD_ERR_PARTIAL :
+        //                $message  = "Fichier '$fileName' non transféré ";
+        //                $message .= ' (problème lors du transfert';
+        //                break;
+        //            case UPLOAD_ERR_NO_TMP_DIR :
+        //                $message  = "Fichier '$fileName' non transféré ";
+        //                $message .= ' (pas de répertoire temporaire).';
+        //                break;
+        //            case UPLOAD_ERR_CANT_WRITE :
+        //                $message  = "Fichier '$fileName' non transféré ";
+        //                $message .= ' (erreur lors de l\'écriture du fichier sur disque).';
+        //                break;
+        //            case UPLOAD_ERR_EXTENSION :
+        //                $message  = "Fichier '$fileName' non transféré ";
+        //                $message .= ' (transfert stoppé par l\'extension).';
+        //                break;
+        //            default :
+        //                $message  = "Fichier '$fileName' non transféré ";
+        //                $message .= ' (erreur inconnue : $code_erreur';
+        //        }
 
         // On teste que les champs ne soient pas vides et soient de bons types
-        if(empty($nom)) {
+        if (empty($nom)) {
             $errors['nameAdvertiser'] = 'Veuillez entrer votre nom';
         }
-        if(!isEmail($email)) {
+        if (!isEmail($email)) {
             $errors['emailAdvertiser'] = 'Veuillez entrer une adresse mail correcte';
         }
-        if(empty($phone) && !is_numeric($phone) ) {
+        if (empty($phone) && !is_numeric($phone)) {
             $errors['phoneAdvertiser'] = 'Veuillez entrer votre numéro de téléphone';
         }
-        if(empty($ville)) {
+        if (empty($ville)) {
             $errors['villeAdvertiser'] = 'Veuillez entrer votre ville';
         }
-        if(!is_numeric($departement)) {
+        if (!is_numeric($departement)) {
             $errors['departmentAdvertiser'] = 'Veuillez choisir un département';
         }
-        if(!is_numeric($categorie)) {
+        if (!is_numeric($categorie)) {
             $errors['categorieAdvertiser'] = 'Veuillez choisir une catégorie';
         }
-        if(empty($title)) {
+        if (empty($title)) {
             $errors['titleAdvertiser'] = 'Veuillez entrer un titre';
         }
-        if(empty($description)) {
+        if (empty($description)) {
             $errors['descriptionAdvertiser'] = 'Veuillez entrer une description';
         }
-        if(empty($price) || !is_numeric($price)) {
+        if (empty($price) || !is_numeric($price)) {
             $errors['priceAdvertiser'] = 'Veuillez entrer un prix';
         }
-        if(empty($password) || empty($password_confirm) || $password != $password_confirm) {
+        if (empty($password) || empty($password_confirm) || $password != $password_confirm) {
             $errors['passwordAdvertiser'] = 'Les mots de passes ne sont pas identiques';
         }
 
@@ -146,15 +147,14 @@ class addItem{
         // S'il y a des erreurs on redirige vers la page d'erreur
         if (!empty($errors)) {
 
-            $template = $twig->loadTemplate("add-error.html.twig");
-            echo $template->render(array(
-                                    "breadcrumb" => $menu,
-                                    "chemin" => $chemin,
-                                    "errors" => $errors)
-                                );
+            return $twig->render($response, "add-error.html.twig", [
+                "breadcrumb" => $menu,
+                "chemin" => $chemin,
+                "errors" => $errors
+            ]);
         }
         // sinon on ajoute à la base et on redirige vers une page de succès
-        else{
+        else {
             $annonce = new Annonce();
             $annonceur = new Annonceur();
 
@@ -165,7 +165,7 @@ class addItem{
             $annonce->ville = htmlentities($allPostVars['ville']);
             $annonce->id_departement = $allPostVars['departement'];
             $annonce->prix = htmlentities($allPostVars['price']);
-            $annonce->mdp = password_hash ($allPostVars['psw'], PASSWORD_DEFAULT);
+            $annonce->mdp = password_hash($allPostVars['psw'], PASSWORD_DEFAULT);
             $annonce->titre = htmlentities($allPostVars['title']);
             $annonce->description = htmlentities($allPostVars['description']);
             $annonce->id_categorie = $allPostVars['categorie'];
@@ -176,8 +176,10 @@ class addItem{
             $annonceur->annonce()->save($annonce);
 
 
-            $template = $twig->loadTemplate("add-confirm.html.twig");
-            echo $template->render(array("breadcrumb" => $menu, "chemin" => $chemin));
+            return $twig->render($response, "add-confirm.html.twig", [
+                "breadcrumb" => $menu,
+                "chemin" => $chemin
+            ]);
         }
     }
-}
\ No newline at end of file
+}
diff --git a/controller/getCategorie.php b/controller/getCategorie.php
index 6f816aa..a20d6c6 100644
--- a/controller/getCategorie.php
+++ b/controller/getCategorie.php
@@ -7,25 +7,29 @@ use model\Annonce;
 use model\Photo;
 use model\Annonceur;
 
-class getCategorie {
-
+class getCategorie
+{
     protected $categories = array();
+    protected $annonce = array();
 
-    public function getCategories() {
+    public function getCategories()
+    {
         return Categorie::orderBy('nom_categorie')->get()->toArray();
     }
 
-    public function getCategorieContent($chemin, $n) {
-        $tmp = Annonce::with("Annonceur")->orderBy('id_annonce','desc')->where('id_categorie', "=", $n)->get();
+    public function getCategorieContent($chemin, $n)
+    {
+        $tmp = Annonce::with("Annonceur")->orderBy('id_annonce', 'desc')
+            ->where('id_categorie', "=", $n)->get();
         $annonce = [];
-        foreach($tmp as $t) {
+        foreach ($tmp as $t) {
             $t->nb_photo = Photo::where("id_annonce", "=", $t->id_annonce)->count();
-            if($t->nb_photo > 0){
+            if ($t->nb_photo > 0) {
                 $t->url_photo = Photo::select("url_photo")
                     ->where("id_annonce", "=", $t->id_annonce)
                     ->first()->url_photo;
-            }else{
-                $t->url_photo = $chemin.'/img/noimg.png';
+            } else {
+                $t->url_photo = $chemin . '/img/noimg.png';
             }
             $t->nom_annonceur = Annonceur::select("nom_annonceur")
                 ->where("id_annonceur", "=", $t->id_annonceur)
@@ -35,20 +39,26 @@ class getCategorie {
         $this->annonce = $annonce;
     }
 
-    public function displayCategorie($twig, $menu, $chemin, $cat, $n) {
-        $template = $twig->loadTemplate("index.html.twig");
+    public function displayCategorie($twig, $menu, $chemin, $cat, $n, $response)
+    {
         $menu = array(
-            array('href' => $chemin,
-                'text' => 'Acceuil'),
-            array('href' => $chemin."/cat/".$n,
-                'text' => Categorie::find($n)->nom_categorie)
+            array(
+                'href' => $chemin,
+                'text' => 'Acceuil'
+            ),
+            array(
+                'href' => $chemin . "/cat/" . $n,
+                'text' => Categorie::find($n)->nom_categorie
+            )
         );
 
         $this->getCategorieContent($chemin, $n);
-        echo $template->render(array(
+
+        return $twig->render($response, "index.html.twig", [
             "breadcrumb" => $menu,
             "chemin" => $chemin,
             "categories" => $cat,
-            "annonces" => $this->annonce));
+            "annonces" => $this->annonce
+        ]);
     }
-}
\ No newline at end of file
+}
diff --git a/controller/index.php b/controller/index.php
index 075971a..b7c84c7 100644
--- a/controller/index.php
+++ b/controller/index.php
@@ -6,23 +6,25 @@ use model\Annonce;
 use model\Photo;
 use model\Annonceur;
 
-class index {
+class index
+{
     protected $annonce = array();
 
-    public function getAll($chemin) {
-//        foreach (Annonce::with("Annonceur")->orderBy('id_annonce', 'desc')->take(12)->get(array('id_annonce', 'id_annonceur', 'id_sous_categorie', 'id_departement', 'prix', 'date', 'titre', 'ville')) as $a) {
-//            array_push($this->annonce, $a->toArray());
-//        }
-        $tmp = Annonce::with("Annonceur")->orderBy('id_annonce','desc')->take(12)->get();
+    public function getAll($chemin)
+    {
+        //        foreach (Annonce::with("Annonceur")->orderBy('id_annonce', 'desc')->take(12)->get(array('id_annonce', 'id_annonceur', 'id_sous_categorie', 'id_departement', 'prix', 'date', 'titre', 'ville')) as $a) {
+        //            array_push($this->annonce, $a->toArray());
+        //        }
+        $tmp = Annonce::with("Annonceur")->orderBy('id_annonce', 'desc')->take(12)->get();
         $annonce = [];
-        foreach($tmp as $t) {
+        foreach ($tmp as $t) {
             $t->nb_photo = Photo::where("id_annonce", "=", $t->id_annonce)->count();
-            if($t->nb_photo > 0){
+            if ($t->nb_photo > 0) {
                 $t->url_photo = Photo::select("url_photo")
                     ->where("id_annonce", "=", $t->id_annonce)
                     ->first()->url_photo;
-            }else{
-                $t->url_photo = $chemin.'/img/noimg.png';
+            } else {
+                $t->url_photo = $chemin . '/img/noimg.png';
             }
             $t->nom_annonceur = Annonceur::select("nom_annonceur")
                 ->where("id_annonceur", "=", $t->id_annonceur)
@@ -32,18 +34,15 @@ class index {
         $this->annonce = $annonce;
     }
 
-    public function displayAllAnnonce($twig, $menu, $chemin, $cat) {
-        $template = $twig->loadTemplate("index.html.twig");
-        $menu = array(
-            array('href' => $chemin,
-                'text' => 'Acceuil'),
-        );
-
+    public function displayAllAnnonce($twig, $menu, $chemin, $cat, $response)
+    {
         $this->getAll($chemin);
-        echo $template->render(array(
+
+        return $twig->render($response, 'index.html.twig', [
             "breadcrumb" => $menu,
             "chemin" => $chemin,
             "categories" => $cat,
-            "annonces" => $this->annonce));
+            "annonces" => $this->annonce
+        ]);
     }
-}
\ No newline at end of file
+}
diff --git a/controller/item.php b/controller/item.php
index 8381210..9ad49c6 100644
--- a/controller/item.php
+++ b/controller/item.php
@@ -1,102 +1,130 @@
 <?php
 
 namespace controller;
+
 use model\Annonce;
 use model\Annonceur;
 use model\Departement;
 use model\Photo;
 use model\Categorie;
 
-class item {
-    public function __construct(){
-    }
-    function afficherItem($twig, $menu, $chemin, $n, $cat) {
-
+class item
+{
+    protected $annonce;
+    protected $annonceur;
+    protected $departement;
+    protected $photo;
+    protected $categItem;
+    protected $dptItem;
+
+    function afficherItem($twig, $menu, $chemin, $n, $cat, $response)
+    {
         $this->annonce = Annonce::find($n);
-        if(!isset($this->annonce)){
-            echo "404";
-            return;
+        if (!isset($this->annonce)) {
+            return $response->withStatus(404);
+        }
+
+        $categorie = Categorie::find($this->annonce->id_categorie);
+        if (!$categorie) {
+            return $response->withStatus(404);
         }
 
         $menu = array(
-            array('href' => $chemin,
-                'text' => 'Acceuil'),
-            array('href' => $chemin."/cat/".$n,
-                'text' => Categorie::find($this->annonce->id_categorie)->nom_categorie),
-            array('href' => $chemin."/item/".$n,
-            'text' => $this->annonce->titre)
+            array(
+                'href' => $chemin,
+                'text' => 'Acceuil'
+            ),
+            array(
+                'href' => $chemin . "/cat/" . $n,
+                'text' => $categorie->nom_categorie
+            ),
+            array(
+                'href' => $chemin . "/item/" . $n,
+                'text' => $this->annonce->titre
+            )
         );
 
         $this->annonceur = Annonceur::find($this->annonce->id_annonceur);
-        $this->departement = Departement::find($this->annonce->id_departement );
+        $this->departement = Departement::find($this->annonce->id_departement);
         $this->photo = Photo::where('id_annonce', '=', $n)->get();
-        $template = $twig->loadTemplate("item.html.twig");
-        echo $template->render(array("breadcrumb" => $menu,
+
+        return $twig->render($response, "item.html.twig", [
+            "breadcrumb" => $menu,
             "chemin" => $chemin,
             "annonce" => $this->annonce,
             "annonceur" => $this->annonceur,
             "dep" => $this->departement->nom_departement,
             "photo" => $this->photo,
-            "categories" => $cat));
+            "categories" => $cat
+        ]);
     }
 
-    function supprimerItemGet($twig, $menu, $chemin,$n){
+    function supprimerItemGet($twig, $menu, $chemin, $n)
+    {
         $this->annonce = Annonce::find($n);
-        if(!isset($this->annonce)){
+        if (!isset($this->annonce)) {
             echo "404";
             return;
         }
         $template = $twig->loadTemplate("delGet.html.twig");
-        echo $template->render(array("breadcrumb" => $menu,
+        echo $template->render(array(
+            "breadcrumb" => $menu,
             "chemin" => $chemin,
-            "annonce" => $this->annonce));
+            "annonce" => $this->annonce
+        ));
     }
 
 
-    function supprimerItemPost($twig, $menu, $chemin, $n, $cat){
+    function supprimerItemPost($twig, $menu, $chemin, $n, $cat)
+    {
         $this->annonce = Annonce::find($n);
         $reponse = false;
-        if(password_verify($_POST["pass"],$this->annonce->mdp)){
+        if (password_verify($_POST["pass"], $this->annonce->mdp)) {
             $reponse = true;
             photo::where('id_annonce', '=', $n)->delete();
             $this->annonce->delete();
-
         }
 
         $template = $twig->loadTemplate("delPost.html.twig");
-        echo $template->render(array("breadcrumb" => $menu,
+        echo $template->render(array(
+            "breadcrumb" => $menu,
             "chemin" => $chemin,
             "annonce" => $this->annonce,
             "pass" => $reponse,
-            "categories" => $cat));
+            "categories" => $cat
+        ));
     }
 
-    function modifyGet($twig, $menu, $chemin, $id){
+    function modifyGet($twig, $menu, $chemin, $id)
+    {
         $this->annonce = Annonce::find($id);
-        if(!isset($this->annonce)){
+        if (!isset($this->annonce)) {
             echo "404";
             return;
         }
         $template = $twig->loadTemplate("modifyGet.html.twig");
-        echo $template->render(array("breadcrumb" => $menu,
+        echo $template->render(array(
+            "breadcrumb" => $menu,
             "chemin" => $chemin,
-            "annonce" => $this->annonce));
+            "annonce" => $this->annonce
+        ));
     }
 
-    function modifyPost($twig, $menu, $chemin, $n, $cat, $dpt){
+    function modifyPost($twig, $menu, $chemin, $n, $cat, $dpt)
+    {
         $this->annonce = Annonce::find($n);
         $this->annonceur = Annonceur::find($this->annonce->id_annonceur);
         $this->categItem = Categorie::find($this->annonce->id_categorie)->nom_categorie;
         $this->dptItem = Departement::find($this->annonce->id_departement)->nom_departement;
 
         $reponse = false;
-        if(password_verify($_POST["pass"],$this->annonce->mdp)){
+        if (password_verify($_POST["pass"], $this->annonce->mdp)) {
             $reponse = true;
-
         }
 
         $template = $twig->loadTemplate("modifyPost.html.twig");
-        echo $template->render(array("breadcrumb" => $menu,
+        echo $template->render(array(
+            "breadcrumb" => $menu,
             "chemin" => $chemin,
             "annonce" => $this->annonce,
             "annonceur" => $this->annonceur,
@@ -104,15 +132,18 @@ class item {
             "categories" => $cat,
             "departements" => $dpt,
             "dptItem" => $this->dptItem,
-            "categItem" => $this->categItem));
+            "categItem" => $this->categItem
+        ));
     }
 
-    function edit($twig, $menu, $chemin, $allPostVars, $id){
+    function edit($twig, $menu, $chemin, $allPostVars, $id)
+    {
 
         date_default_timezone_set('Europe/Paris');
 
-        function isEmail($email) {
-            return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
+        function isEmail($email)
+        {
+            return (preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
         }
 
         /*
@@ -144,31 +175,31 @@ class item {
 
 
         // On teste que les champs ne soient pas vides et soient de bons types
-        if(empty($nom)) {
+        if (empty($nom)) {
             $errors['nameAdvertiser'] = 'Veuillez entrer votre nom';
         }
-        if(!isEmail($email)) {
+        if (!isEmail($email)) {
             $errors['emailAdvertiser'] = 'Veuillez entrer une adresse mail correcte';
         }
-        if(empty($phone) && !is_numeric($phone) ) {
+        if (empty($phone) && !is_numeric($phone)) {
             $errors['phoneAdvertiser'] = 'Veuillez entrer votre numéro de téléphone';
         }
-        if(empty($ville)) {
+        if (empty($ville)) {
             $errors['villeAdvertiser'] = 'Veuillez entrer votre ville';
         }
-        if(!is_numeric($departement)) {
+        if (!is_numeric($departement)) {
             $errors['departmentAdvertiser'] = 'Veuillez choisir un département';
         }
-        if(!is_numeric($categorie)) {
+        if (!is_numeric($categorie)) {
             $errors['categorieAdvertiser'] = 'Veuillez choisir une catégorie';
         }
-        if(empty($title)) {
+        if (empty($title)) {
             $errors['titleAdvertiser'] = 'Veuillez entrer un titre';
         }
-        if(empty($description)) {
+        if (empty($description)) {
             $errors['descriptionAdvertiser'] = 'Veuillez entrer une description';
         }
-        if(empty($price) || !is_numeric($price)) {
+        if (empty($price) || !is_numeric($price)) {
             $errors['priceAdvertiser'] = 'Veuillez entrer un prix';
         }
 
@@ -179,14 +210,16 @@ class item {
         if (!empty($errors)) {
 
             $template = $twig->loadTemplate("add-error.html.twig");
-            echo $template->render(array(
+            echo $template->render(
+                array(
                     "breadcrumb" => $menu,
                     "chemin" => $chemin,
-                    "errors" => $errors)
+                    "errors" => $errors
+                )
             );
         }
         // sinon on ajoute à la base et on redirige vers une page de succès
-        else{
+        else {
             $this->annonce = Annonce::find($id);
             $idannonceur = $this->annonce->id_annonceur;
             $this->annonceur = Annonceur::find($idannonceur);
@@ -198,7 +231,7 @@ class item {
             $this->annonce->ville = htmlentities($allPostVars['ville']);
             $this->annonce->id_departement = $allPostVars['departement'];
             $this->annonce->prix = htmlentities($allPostVars['price']);
-            $this->annonce->mdp = password_hash ($allPostVars['psw'], PASSWORD_DEFAULT);
+            $this->annonce->mdp = password_hash($allPostVars['psw'], PASSWORD_DEFAULT);
             $this->annonce->titre = htmlentities($allPostVars['title']);
             $this->annonce->description = htmlentities($allPostVars['description']);
             $this->annonce->id_categorie = $allPostVars['categorie'];
diff --git a/index.php b/index.php
index 9913d6c..f43e963 100644
--- a/index.php
+++ b/index.php
@@ -1,10 +1,10 @@
 <?php
 require 'vendor/autoload.php';
-use db\connection;
-
-use Slim\Extras\Middleware\CsrfGuard;
 
-use Illuminate\Database\Query\Expression as raw;
+use db\connection;
+use Slim\Factory\AppFactory;
+use Slim\Views\Twig;
+use Slim\Views\TwigMiddleware;
 use model\Annonce;
 use model\Categorie;
 use model\Annonceur;
@@ -13,155 +13,231 @@ use model\Departement;
 
 connection::createConn();
 
+session_start();
 
-$app = new \Slim\Slim(array(
-    'mode' => 'development'
-));
+// Create Container
+$container = new \DI\Container();
 
-if (!isset($_SESSION)) {
-    session_start();
-    $_SESSION['formStarted'] = true;
-}
+// Set view in container
+$container->set('view', function () {
+    $twig = Twig::create('template', [
+        'cache' => false,
+        'debug' => true,
+        'auto_reload' => true
+    ]);
+    return $twig;
+});
+
+// Create app
+AppFactory::setContainer($container);
+$app = AppFactory::create();
 
+// Add routing middleware
+$app->addRoutingMiddleware();
+$app->addErrorMiddleware(true, true, true);
+
+// Add Twig middleware
+$app->add(TwigMiddleware::createFromContainer($app));
+
+// Initialize controllers
+$cat = new \controller\getCategorie();
+$dpt = new \controller\getDepartment();
+
+// Token handling
 if (!isset($_SESSION['token'])) {
     $token = md5(uniqid(rand(), TRUE));
     $_SESSION['token'] = $token;
     $_SESSION['token_time'] = time();
-} else {
-    $token = $_SESSION['token'];
 }
 
-//$app->add(new CsrfGuard());
-
-$loader = new Twig_Loader_Filesystem('template');
-$twig = new Twig_Environment($loader);
-
 $menu = array(
-    array('href' => "./index.php",
-        'text' => 'Accueil')
+    array(
+        'href' => "./index.php",
+        'text' => 'Accueil'
+    )
 );
 
 $chemin = dirname($_SERVER['SCRIPT_NAME']);
 
-$cat = new \controller\getCategorie();
-$dpt = new \controller\getDepartment();
-
-$app->get('/', function () use ($twig, $menu, $chemin, $cat) {
+$app->get('/', function ($request, $response, $args) use ($container, $menu, $cat) {
     $index = new \controller\index();
-    $index->displayAllAnnonce($twig, $menu, $chemin, $cat->getCategories());
+    $chemin = dirname($_SERVER['SCRIPT_NAME']);
+
+    return $index->displayAllAnnonce(
+        $container->get('view'),
+        $menu,
+        $chemin,
+        $cat->getCategories(),
+        $response
+    );
 });
 
 
-$app->get('/item/:n', function ($n) use ($twig, $menu, $chemin, $cat) {
+$app->get('/item/{n}', function ($request, $response, $args) use ($container, $menu, $chemin, $cat) {
     $item = new \controller\item();
-    $item->afficherItem($twig, $menu, $chemin, $n, $cat->getCategories());
+    return $item->afficherItem(
+        $container->get('view'),
+        $menu,
+        $chemin,
+        $args['n'],
+        $cat->getCategories(),
+        $response
+    );
 });
 
-$app->get('/add/', function () use ($twig, $app, $menu, $chemin, $cat, $dpt) {
-
-    $ajout = new controller\addItem();
-    $ajout->addItemView($twig, $menu, $chemin, $cat->getCategories(), $dpt->getAllDepartments());
-
+$app->get('/add', function ($request, $response, $args) use ($container, $menu, $chemin, $cat, $dpt) {
+    $ajout = new \controller\addItem();
+    return $ajout->addItemView(
+        $container->get('view'),
+        $menu,
+        $chemin,
+        $cat->getCategories(),
+        $dpt->getAllDepartments(),
+        $response
+    );
 });
 
-$app->post('/add/', function () use ($twig, $app, $menu, $chemin) {
-
-    $allPostVars = $app->request->post();
-    $ajout = new controller\addItem();
-    $ajout->addNewItem($twig, $menu, $chemin, $allPostVars);
+$app->post('/add', function ($request, $response, $args) use ($container, $menu, $chemin) {
+    $allPostVars = $request->getParsedBody();
+    $ajout = new \controller\addItem();
+    return $ajout->addNewItem(
+        $container->get('view'),
+        $menu,
+        $chemin,
+        $allPostVars,
+        $response
+    );
 });
 
-$app->get('/item/:id/edit', function ($id) use ($twig, $menu, $chemin) {
+$app->get('/item/{id}/edit', function ($request, $response, $args) use ($container, $menu, $chemin) {
     $item = new \controller\item();
-    $item->modifyGet($twig,$menu,$chemin, $id);
+    $item->modifyGet($container->get('view'), $menu, $chemin, $args['id']);
+    return $response;
 });
 
-$app->post('/item/:id/edit', function ($id) use ($twig, $app, $menu, $chemin, $cat, $dpt) {
-    $allPostVars = $app->request->post();
-    $item= new \controller\item();
-    $item->modifyPost($twig,$menu,$chemin, $id, $allPostVars, $cat->getCategories(), $dpt->getAllDepartments());
+$app->post('/item/{id}/edit', function ($request, $response, $args) use ($container, $menu, $chemin, $cat, $dpt) {
+    $allPostVars = $request->getParsedBody();
+    $item = new \controller\item();
+    $item->modifyPost($container->get('view'), $menu, $chemin, $args['id'], $allPostVars, $cat->getCategories(), $dpt->getAllDepartments());
+    return $response;
 });
 
-$app->map('/item/:id/confirm', function ($id) use ($twig, $app, $menu, $chemin) {
-    $allPostVars = $app->request->post();
+$app->map(['GET', 'POST'], '/item/{id}/confirm', function ($request, $response, $args) use ($container, $menu, $chemin) {
+    $allPostVars = $request->getParsedBody();
     $item = new \controller\item();
-    $item->edit($twig,$menu,$chemin, $id, $allPostVars);
-})->name('confirm')->via('GET', 'POST');
-
-$app->get('/search/', function () use ($twig, $menu, $chemin, $cat) {
-    $s = new controller\Search();
-    $s->show($twig, $menu, $chemin, $cat->getCategories());
+    $item->edit($container->get('view'), $menu, $chemin, $args['id'], $allPostVars);
+    return $response;
+})->setName('confirm');
+
+$app->get('/search', function ($request, $response, $args) use ($container, $menu, $chemin, $cat) {
+    $s = new \controller\Search();
+    return $s->show(
+        $container->get('view'),
+        $menu,
+        $chemin,
+        $cat->getCategories(),
+        $response
+    );
 });
 
-
-$app->post('/search/', function () use ($app, $twig, $menu, $chemin, $cat) {
-    $array = $app->request->post();
-
-    $s = new controller\Search();
-    $s->research($array, $twig, $menu, $chemin, $cat->getCategories());
-
+$app->post('/search', function ($request, $response, $args) use ($container, $menu, $chemin, $cat) {
+    $array = $request->getParsedBody();
+    $s = new \controller\Search();
+    return $s->research(
+        $array,
+        $container->get('view'),
+        $menu,
+        $chemin,
+        $cat->getCategories(),
+        $response
+    );
 });
 
-$app->get('/annonceur/:n', function ($n) use ($twig, $menu, $chemin, $cat) {
-    $annonceur = new controller\viewAnnonceur();
-    $annonceur->afficherAnnonceur($twig, $menu, $chemin, $n, $cat->getCategories());
+$app->get('/annonceur/{n}', function ($request, $response, $args) use ($container, $menu, $chemin, $cat) {
+    $annonceur = new \controller\viewAnnonceur();
+    $annonceur->afficherAnnonceur($container->get('view'), $menu, $chemin, $args['n'], $cat->getCategories());
+    return $response;
 });
 
-$app->get('/del/:n', function ($n) use ($twig, $menu, $chemin) {
-    $item = new controller\item();
-    $item->supprimerItemGet($twig, $menu, $chemin, $n);
+$app->get('/del/{n}', function ($request, $response, $args) use ($container, $menu, $chemin) {
+    $item = new \controller\item();
+    $item->supprimerItemGet($container->get('view'), $menu, $chemin, $args['n']);
+    return $response;
 });
 
-$app->post('/del/:n', function ($n) use ($twig, $menu, $chemin, $cat) {
-    $item = new controller\item();
-    $item->supprimerItemPost($twig, $menu, $chemin, $n, $cat->getCategories());
+$app->post('/del/{n}', function ($request, $response, $args) use ($container, $menu, $chemin, $cat) {
+    $item = new \controller\item();
+    $item->supprimerItemPost($container->get('view'), $menu, $chemin, $args['n'], $cat->getCategories());
+    return $response;
 });
 
-$app->get('/cat/:n', function ($n) use ($twig, $menu, $chemin, $cat) {
-    $categorie = new controller\getCategorie();
-    $categorie->displayCategorie($twig, $menu, $chemin, $cat->getCategories(), $n);
+$app->get('/cat/{n}', function ($request, $response, $args) use ($container, $menu, $chemin, $cat) {
+    $categorie = new \controller\getCategorie();
+    return $categorie->displayCategorie(
+        $container->get('view'),
+        $menu,
+        $chemin,
+        $cat->getCategories(),
+        $args['n'],
+        $response
+    );
 });
 
-$app->get('/api(/)', function () use ($twig, $menu, $chemin, $cat) {
-    $template = $twig->loadTemplate("api.html.twig");
+$app->get('/api[/]', function ($request, $response, $args) use ($container, $menu, $chemin, $cat) {
+    $template = $container->get('view')->load("api.html.twig");
     $menu = array(
-        array('href' => $chemin,
-            'text' => 'Acceuil'),
-        array('href' => $chemin . '/api',
-            'text' => 'Api')
+        array(
+            'href' => $chemin,
+            'text' => 'Acceuil'
+        ),
+        array(
+            'href' => $chemin . '/api',
+            'text' => 'Api'
+        )
     );
-    echo $template->render(array("breadcrumb" => $menu, "chemin" => $chemin));
+    $response->getBody()->write($template->render(array(
+        "breadcrumb" => $menu,
+        "chemin" => $chemin
+    )));
+    return $response;
 });
 
-$app->group('/api', function () use ($app, $twig, $menu, $chemin, $cat) {
-
-    $app->group('/annonce', function () use ($app) {
-
-        $app->get('/:id', function ($id) use ($app) {
-            $annonceList = ['id_annonce', 'id_categorie as categorie', 'id_annonceur as annonceur', 'id_departement as departement', 'prix', 'date', 'titre', 'description', 'ville'];
-            $return = Annonce::select($annonceList)->find($id);
+$app->group('/api', function ($app) use ($container, $menu, $chemin, $cat) {
+
+    $app->group('/annonce', function ($app) use ($container) {
+        $app->get('/{id}', function ($request, $response, $args) use ($container) {
+            $annonceList = [
+                'id_annonce',
+                'id_categorie as categorie',
+                'id_annonceur as annonceur',
+                'id_departement as departement',
+                'prix',
+                'date',
+                'titre',
+                'description',
+                'ville'
+            ];
+            $return = Annonce::select($annonceList)->find($args['id']);
 
             if (isset($return)) {
-                $app->response->headers->set('Content-Type', 'application/json');
+                $response = $response->withHeader('Content-Type', 'application/json');
                 $return->categorie = Categorie::find($return->categorie);
                 $return->annonceur = Annonceur::select('email', 'nom_annonceur', 'telephone')
                     ->find($return->annonceur);
-                $return->departement = Departement::select('id_departement', 'nom_departement')->find($return->departement);
-                $links = [];
-                $links["self"]["href"] = "/api/annonce/" . $return->id_annonce;
-                $return->links = $links;
-                echo $return->toJson();
-            } else {
-                $app->notFound();
+                $return->departement = Departement::select('id_departement', 'nom_departement')
+                    ->find($return->departement);
+                $return->links = ["self" => ["href" => "/api/annonce/" . $return->id_annonce]];
+                return $response->write($return->toJson());
             }
+            return $response->withStatus(404);
         });
     });
 
-    $app->group('/annonces(/)', function () use ($app) {
-
-        $app->get('/', function () use ($app) {
+    $app->group('/annonces', function ($app) use ($container) {
+        $app->get('', function ($request, $response, $args) {
             $annonceList = ['id_annonce', 'prix', 'titre', 'ville'];
-            $app->response->headers->set('Content-Type', 'application/json');
+            $response = $response->withHeader('Content-Type', 'application/json');
+
             $a = Annonce::all($annonceList);
             $links = [];
             foreach ($a as $ann) {
@@ -170,17 +246,17 @@ $app->group('/api', function () use ($app, $twig, $menu, $chemin, $cat) {
             }
             $links["self"]["href"] = "/api/annonces/";
             $a->links = $links;
-            echo $a->toJson();
+
+            return $response->write($a->toJson());
         });
     });
 
+    $app->group('/categorie', function ($app) use ($container) {
+        $app->get('/{id}', function ($request, $response, $args) {
+            $response = $response->withHeader('Content-Type', 'application/json');
 
-    $app->group('/categorie', function () use ($app) {
-
-        $app->get('/:id', function ($id) use ($app) {
-            $app->response->headers->set('Content-Type', 'application/json');
             $a = Annonce::select('id_annonce', 'prix', 'titre', 'ville')
-                ->where("id_categorie", "=", $id)
+                ->where("id_categorie", "=", $args['id'])
                 ->get();
             $links = [];
 
@@ -189,40 +265,42 @@ $app->group('/api', function () use ($app, $twig, $menu, $chemin, $cat) {
                 $ann->links = $links;
             }
 
-            $c = Categorie::find($id);
-            $links["self"]["href"] = "/api/categorie/" . $id;
+            $c = Categorie::find($args['id']);
+            if (!$c) {
+                return $response->withStatus(404);
+            }
+
+            $links["self"]["href"] = "/api/categorie/" . $args['id'];
             $c->links = $links;
             $c->annonces = $a;
-            echo $c->toJson();
+
+            return $response->write($c->toJson());
         });
     });
 
-    $app->group('/categories(/)', function () use ($app) {
-        $app->get('/', function () use ($app) {
-            $app->response->headers->set('Content-Type', 'application/json');
-//            $c = Categorie::all(["id_categorie", "nom_categorie"]);
-            $c = Categorie::get();
-            $links = [];
-            foreach ($c as $cat) {
-                $links["self"]["href"] = "/api/categorie/" . $cat->id_categorie;
-                $cat->links = $links;
+    $app->group('/categories', function ($app) use ($container) {
+        $app->get('', function ($request, $response, $args) use ($container) {
+            $response = $response->withHeader('Content-Type', 'application/json');
+            $categories = Categorie::get();
+            foreach ($categories as $cat) {
+                $cat->links = ["self" => ["href" => "/api/categorie/" . $cat->id_categorie]];
             }
-            $links["self"]["href"] = "/api/categories/";
-            $c->links = $links;
-            echo $c->toJson();
+            $categories->links = ["self" => ["href" => "/api/categories/"]];
+            return $response->write($categories->toJson());
         });
     });
 
-    $app->get('/key', function() use ($app, $twig, $menu, $chemin, $cat) {
-        $kg = new controller\KeyGenerator();
-        $kg->show($twig, $menu, $chemin, $cat->getCategories());
+    $app->get('/key', function ($request, $response, $args) use ($container, $menu, $chemin, $cat) {
+        $kg = new \controller\KeyGenerator();
+        $kg->show($container->get('view'), $menu, $chemin, $cat->getCategories());
+        return $response;
     });
 
-    $app->post('/key', function() use ($app, $twig, $menu, $chemin, $cat) {
-        $nom = $_POST['nom'];
-
-        $kg = new controller\KeyGenerator();
-        $kg->generateKey($twig, $menu, $chemin, $cat->getCategories(), $nom);
+    $app->post('/key', function ($request, $response, $args) use ($container, $menu, $chemin, $cat) {
+        $allPostVars = $request->getParsedBody();
+        $kg = new \controller\KeyGenerator();
+        $kg->generateKey($container->get('view'), $menu, $chemin, $cat->getCategories(), $allPostVars['nom']);
+        return $response;
     });
 });
 
-- 
GitLab