PHP code example of decodelabs / greenleaf

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

    

decodelabs / greenleaf example snippets


use DecodeLabs\Greenleaf;

Greenleaf::$namespaces->add('MyApp\\Greenleaf');

use DecodeLabs\Greenleaf;
use DecodeLabs\Harvest;

$dispatcher = Greenleaf::createDispatcher();

$request = Harvest::createRequestFromEnvironment();
$response = $dispatcher->handle($request);


namespace MyApp\Greenleaf;

use DecodeLabs\Greenleaf;
use DecodeLabs\Greenleaf\Generator;
use DecodeLabs\Greenleaf\GeneratorTrait;

class Routes implements Generator
{
    use GeneratorTrait;

    public function generateRoutes(): iterable
    {
        // Basic route
        yield Greenleaf::route('/', 'home');

        // Basic route with parameter
        yield Greenleaf::route('test/{slug}', 'test')

        // Route with inset parameters
        yield Greenleaf::route('test-{slug}/', 'test?hello')
            ->with('slug', validate: 'slug');

        // Route with multi-part path parameters
        yield Greenleaf::route('assets/{path}', 'assets')
            ->with('path', validate: 'path');

        // Redirect
        yield Greenleaf::redirect('old/path', 'new/path');
    }
}

// Route
Greenleaf::route('test/{slug}', 'test?hello');

// Creates URI
Greenleaf::uri('leaf://~front/test?hello');
// $params = ['slug' => 'value-of-slug-in-request']

// Resolves to:
$actionClass = MyApp\Greenleaf\Front\TestAction::class;

// --------------------------
// Or
Greenleaf::route('admin/blog/articles', '~admin/blog/articles');

// Creates URI
Greenleaf::uri('leaf://~admin/blog/articles');

// Resolves to:
$actionClass = MyApp\Greenleaf\Admin\Blog\ArticlesAction::class;

namespace MyApp\Greenleaf\Front;

use DecodeLabs\Harvest;
use DecodeLabs\Harvest\Response;
use DecodeLabs\Greenleaf;
use DecodeLabs\Greenleaf\Action;
use DecodeLabs\Greenleaf\Action\ByMethodTrait;

class TestAction implements Action
{
    use ByMethodTrait;

    public function get(string $slug): Response {
        return Harvest::text('Get response');
    }

    public function post(string $slug): Response {
        return Harvest::text('Post response');
    }
}

use DecodeLabs\Greenleaf;

// route pattern: test/{slug}

$url = Greenleaf::createUrl(
    'test?hello#fragment',
    ['slug' => 'my-slug']
);

// https://mydomain.localtest.me/test/my-slug?hello#fragment