U
U
Uber Noob2018-12-01 09:14:42
PHP
Uber Noob, 2018-12-01 09:14:42

Organizing index.php in a project?

When using a third party router, the project in index.php starts like this:

use Klein\Klein;
require_once __DIR__ . '/vendor/autoload.php';
$klein = new Klein();

$klein->respond('POST', '/packages', function (Request $request) {
    $server = new Server();
    return $server->serve($request->paramsPost()->all());
});
$klein->dispatch();

1. You need to create a session even for an unauthorized user and load some project settings. Where is the best place to do it? Is it correct to call the class immediately after creating the router:
$klein = new Klein();
$session = new Session();
$settings = new Settings();

2. Nowhere is the existence of a class checked before creation. Maybe the Server class doesn't exist. There will be an error. Can it be done like this:
function checkClass($class){
    if (class_exists($class)) {
        return new $class;
    } else {
        ...
    }
}

$klein->respond('GET', '/[:controller]', function ($request) {
    $obj = checkClass(ucfirst($request->controller).'Controller');
    $act = $obj->runDefault();
    return $act;
});

Here https://github.com/nahidex/Employee-Leave-Manageme... in general, all classes were screwed up at once:
use Klein\Klein as Route;
$bag = new Pimple\Container; // container
$route = new Route();
$home = new Home($bag); //controller
$dashboard = new Dashboard($bag); // controller
$user = new User();
$role = new Role();
$leave = new LeaveController($bag);

And if I have 30 of them and not all of them are needed, should I write such a footcloth?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2018-12-01
@Minifets

And if I have 30 of them and not all of them are needed, should I write such a footcloth?

Yes. Objects will not create themselves.

I
Ivan Koryukov, 2018-12-01
@MadridianFox

Yes, you can check for the existence of a class. And if it doesn't exist, then what? Will you use a different class? Probably not, because in 99% of cases this does not happen in a normal situation. No class - fatal error. It's pointless to continue anyway. The error itself will be written to the log, it remains only to configure the web server so that a page with your style gives out a 500 error.
Everything else is handled using the dependency injection system.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question