Spec-Zone.ru › Phalcon 3

Понимание работы приложений Phalcon

Если вы следовали учебнику или сгенерировали код с помощью Phalcon Devtools, вы, возможно, узнаете следующий файл загрузки:

use Phalcon\Mvc\Application;

// Register autoloaders
// ...

// Register services
// ...

// Handle the request
$application = new Application($di);

try {
    $response = $application->handle();

    $response->send();
} catch (\Exception $e) {
    echo "Exception: ", $e->getMessage();
}

Ядро всей работы контроллера происходит при вызове handle():

$response = $application->handle();

Ручная загрузка

Если вы не хотите использовать Phalcon\Mvc\Application, код выше можно изменить следующим образом:

// Get the 'router' service
$router = $di["router"];

$router->handle();

$view = $di["view"];

$dispatcher = $di["dispatcher"];

// Pass the processed router parameters to the dispatcher

$dispatcher->setControllerName(
    $router->getControllerName()
);

$dispatcher->setActionName(
    $router->getActionName()
);

$dispatcher->setParams(
    $router->getParams()
);

// Start the view
$view->start();

// Dispatch the request
$dispatcher->dispatch();

// Render the related views
$view->render(
    $dispatcher->getControllerName(),
    $dispatcher->getActionName(),
    $dispatcher->getParams()
);

// Finish the view
$view->finish();

$response = $di["response"];

// Pass the output of the view to the response
$response->setContent(
    $view->getContent()
);

// Send the response
$response->send();

Следующее замещение Phalcon\Mvc\Application лишено компонента представления, что делает его подходящим для REST-API:

use Phalcon\Http\ResponseInterface;

// Get the 'router' service
$router = $di["router"];

$router->handle();

$dispatcher = $di["dispatcher"];

// Pass the processed router parameters to the dispatcher

$dispatcher->setControllerName(
    $router->getControllerName()
);

$dispatcher->setActionName(
    $router->getActionName()
);

$dispatcher->setParams(
    $router->getParams()
);

// Dispatch the request
$dispatcher->dispatch();

// Get the returned value by the last executed action
$response = $dispatcher->getReturnedValue();

// Check if the action returned is a 'response' object
if ($response instanceof ResponseInterface) {
    // Send the response
    $response->send();
}

Еще один вариант, который перехватывает исключения, генерируемые в диспетчере, и перенаправляет их на другие действия:

use Phalcon\Http\ResponseInterface;

// Get the 'router' service
$router = $di["router"];

$router->handle();

$dispatcher = $di["dispatcher"];

// Pass the processed router parameters to the dispatcher

$dispatcher->setControllerName(
    $router->getControllerName()
);

$dispatcher->setActionName(
    $router->getActionName()
);

$dispatcher->setParams(
    $router->getParams()
);

try {
    // Dispatch the request
    $dispatcher->dispatch();
} catch (Exception $e) {
    // An exception has occurred, dispatch some controller/action aimed for that

    // Pass the processed router parameters to the dispatcher
    $dispatcher->setControllerName("errors");
    $dispatcher->setActionName("action503");

    // Dispatch the request
    $dispatcher->dispatch();
}

// Get the returned value by the last executed action
$response = $dispatcher->getReturnedValue();

// Check if the action returned is a 'response' object
if ($response instanceof ResponseInterface) {
    // Send the response
    $response->send();
}

Хотя вышеперечисленные реализации намного более подробны, чем код, необходимый при использовании Phalcon\Mvc\Application, они предлагают альтернативный способ загрузки вашего приложения. В зависимости от ваших потребностей, вы можете получить полный контроль над тем, что должно быть инициализировано, или заменить определенные компоненты своими собственными, чтобы расширить стандартную функциональность.

© 2011–2017 Phalcon Framework Team
Licensed under the Creative Commons Attribution License 3.0.
https://docs.phalconphp.com/en/latest/reference/applications-explained.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API