The phpcore framework
phpcore is a tiny MVC framework to develop web-based applications in PHP. It's simple and easy to use., (*1)
> composer create-project thnguyendev/phpcore [project folder]
> cd [project folder]
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [QSA,NC,L]
location / {
index index.html index.htm index.php;
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?q=$1;
}
}
php
array (
RouteDefine::controller => "phpcore\\controllers\\HomeController",
RouteDefine::view => "src/server/views/Home.php"
)
);
}
?>
php
getService("phpcore\\core\\RouteService");
$routeService->setRoutes(Routes::paths);
$routeService->mapRoute();
}
}
?>
php
message = "Welcome to Phpcore";
$this->view();
}
}
?>
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Phpcore</title>
</head>
<body>
<h1><?php echo $this->message; ?></h1>
</body>
</html>
Steps to create a Web API with phpcore framework.
1. Follow steps 1 to 3 from Quick start to setup new project.
2. Create Routes [project folder]/src/server/models/Routes.php
php
array (
RouteDefine::controller => "phpcore\\controllers\\GetInfoController"
)
);
}
?>
2. Modify startup file [project folder]/src/server/Startup.php
php
enableCors();
$routeService = $this->getService("phpcore\\core\\RouteService");
$routeService->setRoutes(Routes::paths);
$routeService->mapRoute();
}
}
?>
3. Create an API controller [project folder]/src/server/controllers/api/GetInfoController.php
php
, (*2)
This example will create a Web API that returns data from SQLite with Doctrine, make sure that SQLite PDO has been enabled in PHP configuration.
1. Follow steps 1 to 3 from Quick start to setup new project.
2. Modify file [project folder]/composer.json
json
{
"name": "thnguyendev/phpcore",
"description": "The phpcore framework.",
"version": "3.0.0",
"keywords": ["framework", "phpcore"],
"license": "MIT",
"type": "project",
"autoload": {
"psr-4": {
"phpcore\\": "src/server"
}
},
"require": {
"doctrine/orm": "*"
}
}
Run below command in console to update project
```, (*3)
composer update
3. Create Info class [project folder]/src/server/models/Info.php
php 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; } } ?>4. Create DataService class [project folder]/src/server/services/DataService.php
php '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; } } ?>5. Create database schema with Doctrine command-line interface. First, create configuration file [project folder]/cli-config.php
php getEntityManager()); ?>Then run below command
"vendor/bin/doctrine" orm:schema-tool:create6. Create Routes [project folder]/src/server/models/Routes.php
php array ( RouteDefine::controller => "phpcore\\controllers\\GetInfoController" ) ); } ?>7. Modify startup file [project folder]/src/server/Startup.php
php enableCors(); $routeService = $this->getService("phpcore\\core\\RouteService"); $routeService->setRoutes(Routes::paths); $routeService->mapRoute(); $this->addService(new DataService()); $this->getService("phpcore\\services\\DataService")->initialize(); } } ?>8. Create an API controller [project folder]/src/server/controllers/api/GetInfoController.php
php 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()); } } } ?> ```, (*4)
This example demonstrate authentication with Firebase Jwt.
1. Follow steps 1 to 3 from Quick start to setup new project.
2. Modify file [project folder]/composer.json
json
{
"name": "thnguyendev/phpcore",
"description": "The phpcore framework.",
"version": "3.0.0",
"keywords": ["framework", "phpcore"],
"license": "MIT",
"type": "project",
"autoload": {
"psr-4": {
"phpcore\\": "src/server"
}
},
"require": {
"firebase/php-jwt": "*"
}
}
Run below command in console to update project
```, (*5)
composer update
3. Create AuthorizationService class [project folder]/src/server/services/AuthorizationService.php
php 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); } } } ?>4. Create Routes [project folder]/src/server/models/Routes.php
php array ( RouteDefine::controller => "phpcore\\controllers\\AuthenticateUserController" ), "getinfo" => array ( RouteDefine::controller => "phpcore\\controllers\\GetInfoController", RouteDefine::authorize => true ) ); } ?>5. Modify startup file [project folder]/src/server/Startup.php
php enableCors(); $routeService = $this->getService("phpcore\\core\\RouteService"); $routeService->setRoutes(Routes::paths); $routeService->mapRoute(); $this->addService(new AuthorizationService($this)); $this->getService("phpcore\\services\\AuthorizationService")->authorize(); } } ?>6. Create Authenticate User API controller [project folder]/src/server/controllers/api/AuthenticateUserController.php
php 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); } } ?>7. Create an API controller [project folder]/src/server/controllers/api/GetInfoController.php
php ```, (*6)