PHP code example of bcen / silex-dispatcher

1. Go to this page and download the library: Download bcen/silex-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/ */

    

bcen / silex-dispatcher example snippets


$app->register(new \SDispatcher\SDispatcherServiceProvider());

    class HomeController
    {
        public function get(Request $req)
        {
            return 'Hi, '.$req->getClientIp();
        }
        
        public function post(Request $req)
        {
            return 'This is a post';
        }
    }
    
    $app->match('/', 'HomeController');
    

    class HomeController
    {
        public function get(Request $req)
        {
        }
        
        public function handleMissingMethod(Request $req)
        {
            // HEAD, OPTIONS, PUT, POST everything goes here
            // except GET, which is handle by the above method.
        }
    }
    

    
    $app['my_obj'] = function () {
        $obj = new \stdClass;
        $obj->message = 'hi';
        return $obj;
    };
    
    class HomeController implements \SDispatcher\Common\RequiredServiceMetaProviderInterface
    {
        public function __construct(\stdClass $obj)
        {
            var_dump($obj);
        }
        
        public function get($req)
        {
            return 'Hi, '.$req->getClientIp();
        }

        public static function getRequiredServices()
        {
            return array('my_obj');
        }
    }
    
    $app->match('/', 'HomeController');


    // or by annotation

    use SDispatcher\Common\Annotation as REST;

    /**
     * @REST\RequiredServices("my_obj")
     */
    class HomeController
    {
        public function __construct(\stdClass $obj)
        {
            var_dump($obj);
        }

        public function get($req)
        {
            return 'Hi, '.$req->getClientIp();
        }
    }
    
    


     class NumberListResource
    {
        public function get()
        {
            return array(1, 2, 3, 4, 5, 6);
        }
    }
    
    class NumberDetailResource
    {
        public function get(Request $req, $nid)
        {
            return new \SDispatcher\DataResponse(array(
                'id' => $nid,
                'value' => 'some value',
                'filters' => $req->query->all(),
            ));
        }
    }
    
    $app = new \Silex\Application();
    $app->register(new \SDispatcher\SDispatcherServiceProvider());
    $app['controllers']->setOption('sdispatcher.route.rest', true);

    $app->match('/numbers', 'NumberListResource');
    $app->match('/numbers/{nid}', 'NumberDetailResource');
    
    $app->run();