'Can i combine Slim Framework with plain PHP
I just started with PHP not too long ago and have done some small projects with just plain PHP + Ajax + html. I’m more comfortable with procedural code than OOP. I can still use OOP library of Pakagist. But i want to go slow the first time using a framework.
I want to do a serious new project with Slim but in a procedural way. My ideas:
Only use routing to require a view
My Url: example.com/?r={child router}&page={view}
Routing: Only used to require to a child router and forward $parameter. Template & View: will receive a json result from ajax callback, my app will heavy ajax.
$app->get('/}', function() {
require "index.view";
});
$app->get('/{route}/{page}', function (Request $request, Response $response, array $args) {
$route = $args['route'] ? $args['route'] : "";
$page = $args['page'] ? $args['page'] : "";
// I have a folder View contains folder User
if folder_exists("route/" . $route)
{
if file_exists("view/" . $route . "/" . $page . ".php")
{
require ("view/" . $route . "/" . $page . ".php");
} else {
require ("view/" . $route . "/def_page.php");
}
} else {
header (Location: index.php);
}
});
// example.com/?r=user&page=register
// will require view/user/register.php
// example.com/?r=admin&page=login
// will require view/admin/login.php
And all my logic will be handled through an ajax route like
$app->get('/ajax/{route}/{action}', function (Request $request, Response $response, array $args) {
$route = $args['route'] ? $args['route'] : "";
$action= $args['action'] ? $args['action'] : "";
// I have a folder View contains folder User
if file_exists("ajax/" . $route . "/" . $page . ".php")
{
require ("ajax/" . $route . "/" . $page . ".php");
} else {
$result = [
'status' => false,
'msg' => 'failed'
]
return json_encode($result);
}
});
// example.com/?r=ajax&action=login
// will require ajax/user/login.php
Please help me and let me know if this doesn’t fit in Slim or anything bad. Thanks for help.
UPDATE: I used this route library. It very simple and nice. Slim 4, he's slim but very complex.
<?php
use Core\Libs\View;
use Core\Libs\Config;
$route = new AltoRouter();
$route->map( 'GET', '/', ['route' => 'core', 'page' => 'landing']);
$route->map( 'GET', '/user', ['route' => 'user', 'page' => 'home']);
$route->map( 'GET', '/user/login', ['route' => 'user', 'page' => 'login']);
$match = $route->match();
?>
Target: <?php var_dump($match['target']); ?><br>
Params: <?php var_dump($match['params']); ?><br>
Name: <?php var_dump($match['name']); ?><br>
<?
if( is_array($match) && isset( $match['target'] ) ) {
//call_user_func_array( $match['target'], $match['params'] );
var_dump($match);
} else {
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
echo 'Không tìm thấy trang';
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
