Search code examples
phpaltorouter

How to call controller->method with alto router


I'm trying to learn how to use alto router and what I want i'ts "pretty simple".

exemple:

  • "/" should call "AppController->index()"
  • "/profil" should call "ProfilController->profil()"
  • /profil/1" should call "ProfilController->profilById()

etc...

This is what I've tried so far:

<?php
use App\Controller\AppController;
require './vendor/autoload.php';
putenv("BASE_URL=/formulaire-php");
 
// Router
$router = new AltoRouter();
$router->setBasePath('/formulaire-php');
$router->map('GET', '/', 'AppController#index');
$match = $router->match();

if ($match === false) {
    echo "404";
} else {
    list($controller, $action) = explode('#', $match['target']);
    if (is_callable(array($controller, $action))) {
        call_user_func_array(array($controller,$action), array($match['params']));
    } else {
        // here your routes are wrong.
        // Throw an exception in debug, send a  500 error in production
    }
}

htaccess:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]

composer.json

{
  "require": {
    "altorouter/altorouter": "^2.0"
  },
  "autoload": {
    "psr-4": {
      "App\\": "src/controller/"
    }
  }
}

AppController:


namespace App\Controller;

class AppController
{
    public function index()
    {
        echo "I index code + return index view here";
    }

for now I have no error at all so it's difficult to know what's going on..


Solution

  • I found the solution:

    Solution 1 : Put all routes in index.php

    index.php

    $router = new AltoRouter();
    $router->setBasePath('/formulaire-php');
    $router->map('GET', '/', 'AppController#create') //controller#method
    $match = $router->match();
     
    
    if (!$match) {
        echo "404";
        die;
    }
    
    if ($match) {
        require_once './src/view/template/header.php';
        list($controller, $action) = explode('#', $match['target']);
        $controller = 'App\\Controller\\' . $controller;
        $controller = new $controller;
        if (is_callable(array($controller, $action))) {
            call_user_func_array(array($controller,$action), array($match['params']));
        }
        require_once './src/view/template/footer.php';
    }
    

    composer.json

      "autoload": {
        "psr-4": {
          "App\\": "src/"
        }
      }
    

    AppController

    namespace App\Controller;
    
    use App\Repository\UserRepository;
    
    class AppController extends AbstractController
    {
        public function create()
        {
            echo "hello"
        }
    

    solution2 : put the routes in a config/routes.php and call it in index.php

    src/Config/Routes.php

    namespace App\Config;
    
    class Routes
    {
    //The method getRoutes() will return a array with all routes
        public static function getRoutes(): array
        {
            return [
              ['GET', '/', 'AppController#create'],
              ['POST', '/save', 'AppController#save'],
              ['GET', '/save', 'AppController#save'],
              ['GET', '/user/[i:id]', 'AppController#test'],
            ];
        }
    }
    

    index.php The foreach loop will loop over all routes.

    <?php
    
    require './vendor/autoload.php';
    
    use App\Config\Routes;
    
    // Router
    $router = new AltoRouter();
    $router->setBasePath('/formulaire-php');
    
    foreach (Routes::getRoutes() as $route) {
        $router->map(...$route);
    }
    
    $match = $router->match();
     
    
    if (!$match) {
        echo "404";
        die;
    }
    
    if ($match) {
        require_once './src/view/template/header.php';
        list($controller, $action) = explode('#', $match['target']);
        var_dump($controller);
        $controller = 'App\\Controller\\' . $controller;
        $controller = new $controller;
        if (is_callable(array($controller, $action))) {
            call_user_func_array(array($controller,$action), array($match['params']));
        }
        require_once './src/view/template/footer.php';
    }