PHP code example of crodas / dispatcher

1. Go to this page and download the library: Download crodas/dispatcher library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

crodas / dispatcher example snippets


use Symfony\Component\HttpFoundation\Request;

/** 
 * A single function can have multiple routes.
 * 
 * @Route("/{user}") 
 * @Route("/user/{user}")
 */
function handler(Request $req, $user)
{
  return "Hello {$user}";
}

/**
 *  You can also set default values and use multiple routes
 *
 *  @Route("/foo/{bar}")
 *  @Route("/foo", {bar="index"})
 */
function do_something_with_bar(Request $request, $bar) {
  print "I've got bar=" . $bar;
}

/**
 *  If @Route is define at a class it would behave as a
 *  namespace of prefix for the routes defined at their
 *  methods
 *
 *  @Route("/admin")
 */
class Foobar
{
  /**
   *  This handles POST /admin/login
   *
   *  @Route("/login")
   *  @Method POST
   */
  public function do_login(Request $req)
  {
  }
  
  /**
   *  This handles GET /admin/login
   *
   *  @Route("/login")
   */
  public function login(Request $req)
  {
  }
}

$router = new Dispatcher\Router;
$router->
  // where our controllers are located
  ->addDirectory(__DIR__ . "/../projects");

// Do the router
$router->doRoute();

$router->development();


/**
 * In this URL, the placeholder user have a Filter, that means
 * if the controller is called we can be sure we get a valid
 * user object.
 *
 * @Route("/profile/{user}")
 */
function show_profile(Request $req, $user) {
  return "Hi {$user->name}";
}


/**
 * Validate {user} placeholders
 *
 * Check if the user exists in the database, if it does exists
 * it will return true and the controller will be called.
 *
 * @Filter("user") 
 */
function some_filter(Request $req, $name, $value) {
  $userobj = DB::getUserById($value);
  if ($userobj) {
    /* I'm overriding the placeholder $name for an object of the Database */
    $req->attributes->set($name, $userobj);
    return true;
  }
  return false;
}