PHP code example of h4d / leveret

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

    

h4d / leveret example snippets


    $app = new Application();
    $app->registerRoute('GET', '/hello/:string')
        ->setAction(
            function ($name) use ($app)
            {
                $app->getResponse()->setBody('Hello '.$name);
            });
    $app->run();

    // Action with multiple params.
    $app->registerRoute('GET', '/add/:(float)num1/:(float)num2')
        ->setAction(
            function ($num1, $num2) use ($app)
            {
                $result = $num1 + $num2;
                $app->getLogger()->notice(sprintf('Result: %f', $result), ['num1' => $num1,
                                                                           'num2' => $num2,
                                                                           'result' => $result]);
                $app->getResponse()->setBody($result));
            });

    $app->registerRoute('GET', '/hello/:name')
        ->setAction(
            function ($name) use ($app)
            {
                $app->getView()->addVar('name', $name);
                $app->render('hello.phtml');
            })
        ->addPreDispatchAction(
            function ($route, $app)
            {
                $newParams = array();
                /** @var \H4D\Leveret\Application\Route $route */
                foreach($route->getParams() as $key => $value)
                {
                    $newParams[$key] = is_string($value) ? strtoupper($value) : $value;
                }
                $route->setParams($newParams);
            })

    $app = new Application(APP_CONFIG_DIR.'/config.ini');
    $app->setAutoRequestValidationMode(Application::AUTO_REQUEST_VALIDATION_MODE_REQUEST_VALIDATION_BEFORE_AUTH);

    $this->registerRoute('POST', '/create/alias')
            ->addRequestFilters('alias', [new Filter1(), new Filter2(), 
                                         function($alias){return strtolower($alias)}]);

    $app->run();

    use H4D\Leveret\Application;
    use H4D\Leveret\Application\Controller;
    use H4D\Leveret\Http\Response\Headers;
    
    class MathController extends Controller
    {
       /**
        * Sobreescribo método init
        */
        public function init()
        {
            // Especifico el layout que se utilizará para todas las acciones de este controller
            $this->useLayout('layouts/main.phtml');
        }
        
        /**
         * @param float $a
         * @param float $b
         */
        public function add($a, $b)
        {
            // Obtengo la vista y paso las variables necesarias.
            $this->getView()
                ->addVar('title', sprintf('%s + %s', $a, $b))
                ->addVar('num1', $a)
                ->addVar('num2', $b)
                ->addVar('result', $a+$b);
            // Especifico la pantilla que se va a emplear.    
            $this->render('add.phtml');
        }
    
        public function info()
        {
            // No uso vista, seteo directamente el cuerpo de la respuesta.
            $this->getResponse()->setBody(phpinfo());
        }
    }

    <html>
    <head>
        <title> echo $title

    <div>
         echo $this->partial(APP_VIEWS_DIR.'/partials/test/test.phtml', ['nombre'=>'Pakito']);

    <div>
         echo $this->partial(APP_VIEWS_DIR.'/partials/test/partial.phtml', ['nombre'=>'Pakito']);

    <h1>Partial</h1>
    <p>
         echo $this->translate('Hola %s! Esto es un partial.', $nombre);

    <h2>Partial interno</h2>
     echo $this->translate('Hola %s! Soy un partial dentro de otro partial', $nombre);

        $app->registerService('ServiceName', function ()
        {
            $configFile = IniFile::load(APP_CONFIG_DIR . '/sample.ini');
            $myService = new MyService($configFile);

            return $myService;
        }, true);

        $app->registerService('ServiceName', function ()
        {
            $configFile = IniFile::load(APP_CONFIG_DIR . '/sample.ini');
            $myService = new MyService($configFile);

            return $myService;
        }, false);

$this->registerAclForController($this->getService(AdminLoggedInRequired::class),
                                'MyAppp\Controller\AdminController');

    
    
    use H4D\Leveret\Application;
    use H4D\Leveret\Http\Response;
    use H4D\Leveret\Http\Response\Headers;
    use H4D\Logger;
    
    ///////////////////////////////////////////////////
    // INI: Register routes and actions ////////////////////////////////////////////////////////////////
    
    // Simple action without params returning html contents using a template.
    $app->registerRoute('GET', '/')
        ->setAction(
            function () use ($app)
            {
                $app->getLogger()->notice('It works!');
                $app->render('default.phtml');
            });
    
    // Action with one param, multiple predispatch actions and one postdispatch action returning html
    // contents using a template.
    $app->registerRoute('GET', '/hello/:name')
        ->setAction(
            function ($name) use ($app)
            {
                $app->getLogger()->notice('Hello', array('name' => $name));
                $app->getView()->addVar('name', $name);
                $app->render('hello.phtml');
            })
        ->addPreDispatchAction(
            function ($route, $app)
            {
                $newParams = array();
                /** @var \H4D\Leveret\Application\Route $route */
                foreach($route->getParams() as $key => $value)
                {
                    $newParams[$key] = is_string($value) ? strtoupper($value) : $value;
                }
                $route->setParams($newParams);
            })
        ->addPreDispatchAction(
            function ($route, $app)
            {
                $newParams = array();
                /** @var \H4D\Leveret\Application\Route $route */
                foreach($route->getParams() as $key => $value)
                {
                    $newParams[$key] = is_string($value) ?
                        '"' . $value . '"' : $value;
                }
                $route->setParams($newParams);
            })
        ->addPostDispatchAction(
            function ($route, $app)
            {
                /** @var Application $app */
                $app->getResponse()->setStatusCode('404');
            }
        );
    
    // Action with multiple params returning JSON content type.
    $app->registerRoute('GET', '/add/:(float)num1/:(float)num2')
        ->setAction(
            function ($num1, $num2) use ($app)
            {
                $result = $num1 + $num2;
                $app->getLogger()->notice(sprintf('Result: %f', $result), array('num1' => $num1,
                                                                                'num2' => $num2,
                                                                                'result' => $result));
                // Change response headers.
                $app->getResponse()->getHeaders()->setContentType(Headers::CONTENT_TYPE_JSON);
                $app->getResponse()->setBody(json_encode(array('num1' => $num1,
                                                               'num2' => $num2,
                                                               'result' => $result)));
            })
        ->addPreDispatchAction(function ($route, $app)
        {
            /** @var Application $app */
            if ($app->getRequest()->hasAuth())
            {
                $user = $app->getRequest()->getAuthUser();
                $pass = $app->getRequest()->getAuthPassword();
                $app->getLogger()->debug(sprintf('User: %s, Pass: %s', $user, $pass));
            }
    
        });
    
    // END: Register routes and actions ////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////
    
    // Run the application!
    $app->run();