PHP code example of thnguyendev / phpcore

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

    

thnguyendev / phpcore example snippets


    
        namespace phpcore\models;

        use phpcore\core\RouteDefine;

        class Routes {
            public const paths = array(
                "" => array (
                    RouteDefine::controller => "phpcore\\controllers\\HomeController",
                    RouteDefine::view => "src/server/views/Home.php"
                )
            );
        }
    

    
        namespace phpcore;

        use phpcore\core\App;
        use phpcore\models\Routes;

        class Startup extends App {
            public function __construct() {
                parent::__construct();
                $routeService = $this->getService("phpcore\\core\\RouteService");
                $routeService->setRoutes(Routes::paths);
                $routeService->mapRoute();
            }
        }
    

    
        namespace phpcore\controllers;

        use phpcore\core\Controller;

        class HomeController extends Controller {
			public $message;
			public function process() {
				$this->message = "Welcome to Phpcore";
				$this->view();
			}
		}
    

    
        namespace phpcore\models;

        use phpcore\core\RouteDefine;

        class Routes {
            public const paths = array(
                "getinfo" => array (
                    RouteDefine::controller => "phpcore\\controllers\\GetInfoController"
                )
            );
        }
    

    
        namespace phpcore;

        use phpcore\core\App;
        use phpcore\models\Routes;

        class Startup extends App {
            public function __construct() {
                parent::__construct();
                $this->enableCors();
                $routeService = $this->getService("phpcore\\core\\RouteService");
                $routeService->setRoutes(Routes::paths);
                $routeService->mapRoute();
            }
        }
    

    
        namespace phpcore\controllers;

        use phpcore\core\ApiController;
        use phpcore\core\ContentType;

        class GetInfoController extends ApiController {
            public function get() {
                ContentType::applicationJson();
                echo("{ 'Name': 'Phpcore', 'Author': 'Hung Thanh Nguyen' }");
            }
        }
    

    
        namespace phpcore\models;

        use Doctrine\ORM\Mapping as ORM;

        /**
        * @ORM\Entity
        * @ORM\Table(name="Info")
        **/
        class Info {
            /**
            * @ORM\Id
            * @ORM\Column(type="integer")
            * @ORM\GeneratedValue
            * @var int
            **/
            private $ID;

            /**
            * @ORM\Column(type="string")
            * @var string
            **/
            private $Name;

            /**
            * @ORM\Column(type="string")
            * @var string
            **/
            private $Author;

            public function getID() {
                return $this->ID;
            }

            public function getName() {
                return $this->Name;
            }

            public function setName($name) {
                $this->Name = $name;
            }

            public function getAuthor() {
                return $this->Author;
            }

            public function setAuthor($author) {
                $this->Author = $author;
            }
        }
    

    
        namespace phpcore\services;

        use Exception;
        use Doctrine\ORM\Tools\Setup;
        use Doctrine\ORM\EntityManager;
        use phpcore\models\Info;

        class DataService {

            private $entityManager;

            public function __construct() {
                try {
                    // Create a simple "default" Doctrine ORM configuration for Annotations
                    $isDevMode = true;
                    $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__ . "/../models"), $isDevMode, null, null, false);

                    // database configuration parameters for Sqlite
                    $conn = array(
                        'driver' => 'pdo_sqlite',
                        'path' => __DIR__ . '/../db.sqlite',
                    );

                    // obtaining the entity manager
                    $this->entityManager = EntityManager::create($conn, $config);
                }
                catch (Exception $e) {
                    throw $e;
                }
            }

            public function initialize() {
                try {
                    $infoRepository = $this->entityManager->getRepository("phpcore\\models\\Info");
                    $info = $infoRepository->findAll();
                    if (count($info) == 0) {
                        $newInfo = new Info();
                        $newInfo->setName("Phpcore");
                        $newInfo->setAuthor("Hung Thanh Nguyen");
                        $this->entityManager->persist($newInfo);
                        $this->entityManager->flush();
                    }
                }
                catch (Exception $e) {
                    throw $e;
                }
            }

            public function getEntityManager() {
                return $this->entityManager;
            }
        }
    

    
        re\services\DataService;

        $dataService = new DataService();
        return \Doctrine\ORM\Tools\Console\ConsoleRunner::createHelperSet($dataService->getEntityManager());
    

    
        namespace phpcore\models;

        use phpcore\core\RouteDefine;

        class Routes {
            public const paths = array(
                "getinfo" => array (
                    RouteDefine::controller => "phpcore\\controllers\\GetInfoController"
                )
            );
        }
    

    
        namespace phpcore;

        use phpcore\core\App;
        use phpcore\models\Routes;
        use phpcore\services\DataService;

        class Startup extends App {
            public function __construct() {
                parent::__construct();
                $this->enableCors();
                $routeService = $this->getService("phpcore\\core\\RouteService");
                $routeService->setRoutes(Routes::paths);
                $routeService->mapRoute();

                $this->addService(new DataService());
                $this->getService("phpcore\\services\\DataService")->initialize();
            }
        }
    

    
        namespace phpcore\controllers;

        use Exception;
        use phpcore\core\ApiController;
        use phpcore\core\ContentType;
        use phpcore\core\HttpCodes;

        class GetInfoController extends ApiController {
            public function get() {
                $dataService = $this->getApp()->getService("phpcore\\services\\DataService");
                if (!isset($dataService)) {
                    throw new Exception("Data service not found", HttpCodes::internalServerError);
                }
                $entityManager = $dataService->getEntityManager();
                $infoRepository = $entityManager->getRepository("phpcore\\models\\Info");
                $info = $infoRepository->findAll();
                if (count($info) > 0) {
                    ContentType::applicationJson();
                    printf("{ 'Name': '%s', 'Author': '%s' }", $info[0]->getName(), $info[0]->getAuthor());
                }
            }
        }
    

    
        namespace phpcore\services;

        use Exception;
        use phpcore\core\HttpCodes;
        use phpcore\core\RouteDefine;
        use Firebase\JWT\JWT;

        class AuthorizationService {
            private const key = "example_key";
            private $app;

            public function __construct($app) {
                $this->app = $app;
            }

            public function authenticate($input) {
                $jwt = null;   
                if ($input->userName === "admin" && $input->password === "nopassword") {
                    $requestService = $this->app->getService("phpcore\\core\\RequestService");
                    if (!isset($requestService)) {
                        throw new Exception("Request service not found", HttpCodes::internalServerError);
                    }
                    $time = time();
                    $payload = [
                        'iss' => $requestService->getServer()["Name"],
                        'iat' => $time,
                        'nbf' => $time + 10,
                        'exp' => $time + 600,
                        'user' => [
                            'userName' => $input->userName
                        ]
                    ];
                    $jwt = JWT::encode($payload, $this::key);
                }
                return $jwt;
            }

            public function authorize() {
                $requestService = $this->app->getService("phpcore\\core\\RequestService");
                if (!isset($requestService)) {
                    throw new Exception("Request service not found", HttpCodes::internalServerError);
                }
                $routeService = $this->app->getService("phpcore\\core\\RouteService");
                if (!isset($routeService)) {
                    throw new Exception("Route service not found", HttpCodes::internalServerError);
                }
                $authorized = true;
                $route = $routeService->getRoute();
                if (isset($route)) {
                    if (isset($route[RouteDefine::authorize]) && $route[RouteDefine::authorize] === true) {
                        $authorized = false;
                        if (isset($requestService->getHeader()["Authorization"])) {
                            list($jwt) = sscanf($requestService->getHeader()["Authorization"], "Bearer %s");
                            if ($jwt) {
                                try {
                                    $token = JWT::decode($jwt, $this::key, array("HS256"));
                                    $authorized = true;
                                }
                                catch(Exception $e) { }
                            }
                        }
                    }
                }
                if (!$authorized) {
                    throw new Exception("Authorization failed", HttpCodes::unauthorized);
                }
            }
        }
    

    
        namespace phpcore\models;

        use phpcore\core\RouteDefine;

        class Routes {
            public const paths = array(
                "authenticate" => array (
                    RouteDefine::controller => "phpcore\\controllers\\AuthenticateUserController"
                ),
                "getinfo" => array (
                    RouteDefine::controller => "phpcore\\controllers\\GetInfoController",
                    RouteDefine::authorize => true
                )
            );
        }
    

    
        namespace phpcore;

        use phpcore\core\App;
        use phpcore\models\Routes;
        use phpcore\services\AuthorizationService;

        class Startup extends App {
            public function __construct() {
                parent::__construct();
                $this->enableCors();
                $routeService = $this->getService("phpcore\\core\\RouteService");
                $routeService->setRoutes(Routes::paths);
                $routeService->mapRoute();

                $this->addService(new AuthorizationService($this));
                $this->getService("phpcore\\services\\AuthorizationService")->authorize();
            }
        }
    

    
        namespace phpcore\controllers;

        use phpcore\core\ApiController;
        use phpcore\core\ContentType;

        class AuthenticateUserController extends ApiController {
            public function post() {
                $requestService = $this->getApp()->getService("phpcore\\core\\RequestService");
                if (!isset($requestService)) {
                    throw new Exception("Request service not found", HttpCodes::internalServerError);
                }
                $authorizationService = $this->getApp()->getService("phpcore\\services\\AuthorizationService");
                if (!isset($authorizationService)) {
                    throw new Exception("Authorization service not found", HttpCodes::internalServerError);
                }
                $input = json_decode($requestService->getBody());
                $jwt = $authorizationService->authenticate($input);
                ContentType::applicationJson();
                printf("{ 'token': '%s' }", $jwt);
            }
        }
    

    
        namespace phpcore\controllers;

        use Exception;
        use phpcore\core\ApiController;
        use phpcore\core\ContentType;
        use phpcore\core\HttpCodes;

        class GetInfoController extends ApiController {
            public function get() {
                ContentType::applicationJson();
                echo("{ 'Name': 'Phpcore', 'Author': 'Hung Thanh Nguyen' }");
            }
        }
    

    location / {
        index  index.html index.htm index.php;
        if (!-e $request_filename) {
            rewrite ^(.*)$ /index.php?q=$1;
        }
    }