PHP code example of nddcoder / rest

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

    

nddcoder / rest example snippets


class Router extends BaseRouter
{
    protected function register(RouteCollector $routes): void
    {
        $routes->get('/', HomeController::class); //using invokeable controller
        $routes->get('/home', [HomeController::class, 'home']);
        $routes->get('/hello/{name}', [HomeController::class, 'hello']);
        
        /*
        $routes->post(...)
        $routes->put(...)
        $routes->delete(...)
        */
    }
}

class HomeController
{
    public function __invoke(ServerRequestInterface $request)
    {
        $frameworkVersion = Application::VERSION;
        return view('home.twig', compact('frameworkVersion'));
    }

    public function home()
    {
        return response()->redirect('/');
    }
    
    public function hello(ServerRequestInterface $request, $name)
    {
        return "Hello $name";
    }
}

Application::getInstance()
    ->onBoot(function (Application $app) {
        $app->bind(ProductServiceInterface::class, fn($app) => new ProductServiceImpl());
    });


use Rest\Contracts\Singleton;

class SlackService extends Singleton {

}

//or

Application::getInstance()
    ->onBoot(function (Application $app) {
        $app->singleton(SlackService::class, SlackService::class);
    });

class ProductController
{
    protected ProductServiceInterface $productService;
    
    public function __construct(ProductServiceInterface $service)
    {
        $this->productService = $service;
    }
}

class ProductController
{
    public function __construct()
    {
        $this->productService = app(ProductServiceInterface::class);
        //or
        $this->productService = app()->make(ProductServiceInterface::class);
    }
}

$application = app(); //return Application instance
$classInstance = app(ClassName::class); //ClassName instance

class ProductController
{
    public function index()
    {
        $products = [
            //...
        ];
        
        return view('products.index', [
            'products' => $products
        ]);
    }
}

class ProductController
{
    public function index()
    {
        $products = [
            //...
        ];
        
        return response()->json([
           'data' => $products
        ]);
    }
}

$debug = env('APP_DEBUG') == 'true';

dd($var1, $var2, $var3);

abort(500);
abort(403, 'Permission Denied');

abort_if($condition, $status, $messagge);

abort_unless($condition, $status, $messagge);

logger('Error occurred');
logger($exeption);


php index.php

nodemon index.php