How router/roites could be injected in application in phalcon framework? - php

Here, in docs, is written about how to create routes:
http://docs.phalconphp.com/en/latest/reference/routing.html
But i can't find how i can inject them in application.
What i need to do, to make my application use defined routes?
Should i inject router (or how?)

The router can be registered in the DI (in your public/index.php) this way:
$di->set('router', function() {
$router = new \Phalcon\Mvc\Router();
$router->add("/login", array(
'controller' => 'login',
'action' => 'index',
));
$router->add("/products/:action", array(
'controller' => 'products',
'action' => 1,
));
return $router;
});
Also is possible to move the registration of routes to a separate file in your application (i.e app/config/routes.php) this way:
$di->set('router', function(){
require __DIR__.'/../app/config/routes.php';
return $router;
});
Then in the app/config/routes.php file:
<?php
$router = new \Phalcon\Mvc\Router();
$router->add("/login", array(
'controller' => 'login',
'action' => 'index',
));
$router->add("/products/:action", array(
'controller' => 'products',
'action' => 1,
));
return $router;
Examples: https://github.com/phalcon/php-site/blob/master/public/index.php#L33 and https://github.com/phalcon/php-site/blob/master/app/config/routes.php

Related

defined route is missing - Missing Route in Cakephp 3.4

I am trying to use the prefix "student". When I create a link in template or layout file I am getting this error as shown in the image:
code in routes.php
<?php
use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
use Cake\Routing\Route\DashedRoute;
Router::defaultRouteClass(DashedRoute::class);
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
$routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
$routes->fallbacks(DashedRoute::class);
});
Router::prefix('admin', function ($routes) {
$routes->connect('/users/', [ 'controller' => 'MyUsers', 'action' => 'index', 'plugin'=>false]);
$routes->connect('/login', [ 'controller' => 'MyUsers', 'action' => 'login', 'plugin'=>false, 'prefix'=>'admin']);
$routes->connect('/', [ 'controller' => 'MyUsers', 'action' => 'dashboard', 'plugin'=>false]);
$routes->fallbacks(DashedRoute::class);
});
Router::prefix('trainer', function ($routes) {
$routes->connect('/users/', [ 'controller' => 'MyUsers', 'action' => 'index', 'plugin'=>false]);
$routes->connect('/login', [ 'controller' => 'MyUsers', 'action' => 'login', 'plugin'=>false]);
$routes->connect('/', [ 'controller' => 'MyUsers', 'action' => 'dashboard', 'plugin'=>false]);
$routes->fallbacks(DashedRoute::class);
});
Router::prefix('student', function ($routes) {
$routes->connect('/courses/', array ( 'controller' => 'Courses', 'action' => 'index', 'plugin' => false, 'prefix' => 'student', '_ext' => NULL, ));
$routes->connect('/', array ( 'controller' => 'MyUsers', 'action' => 'dashboard', 'plugin' => false));
});
/**
* Load all plugin routes. See the Plugin documentation on
* how to customize the loading of plugin routes.
*/
Plugin::routes();
layout file student.ctp has only one line of code:
<li><?php echo $this->Html->link('Courses', [ 'controller' => 'Courses', 'action' => 'index', 'plugin' => false, 'prefix' => 'student', '_ext' => NULL, ]);?></li>
AppController.php:
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
class AppController extends Controller
{
public $helpers = array(
'CakeDC/Users.AuthLink',
'CakeDC/Users.User',
);
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('CakeDC/Users.UsersAuth');
$this->loadComponent('Utils.GlobalAuth');
$this->Auth->config('loginRedirect', array('controller'=>'Courses', 'action'=>'index', 'plugin'=>FALSE));
$this->Auth->config('logoutRedirect', array('controller'=>'MyUsers', 'action'=>'login', 'plugin'=>FALSE));
$this->Auth->config('unauthorizedRedirect', array('controller'=>'Courses', 'action'=>'index', 'prefix'=>$this->Auth->user('role')));
$this->Auth->config('loginAction', array('controller'=>'MyUsers', 'action'=>'login'));
$this->Auth->allow(['login', 'logout']);
}
public function beforeRender(Event $event)
{
if (!array_key_exists('_serialize', $this->viewVars) &&
in_array($this->response->type(), ['application/json', 'application/xml'])
) {
$this->set('_serialize', true);
}
$this->_renderLayout();
}
private function _renderLayout()
{
$prefix = isset($this->request->params['prefix'])?$this->request->params['prefix']:FALSE;
if(!$prefix)
{
return;
}
$this->viewBuilder()->setLayout($prefix);
}
}
I have checked this solution : CakePHP 3: Missing route error for route that exists
You cannot feed the special plugin key with a boolean, it must either be null, or a string with the name of the plugin.
Also there is no need to define the plugin or prefix keys when connecting routes, the Router::prefix() method will take care of adding the prefix. Similarily Router::plugin() will add the plugin name, and when not using Router::plugin(), a default of null is being assumed for the plugin key.
Furthermore defining _ext with null only makes sense if you want to disallow generating URLs with extensions. And specifying it when generating URLs is only neccessary when it has been defined as a non-null value, which is also true for the plugin key (unless you need to break out of the current plugin context).
Long story short, connecting the route only requires the controller and action keys:
$routes->connect('/courses/', [
'controller' => 'Courses',
'action' => 'index'
]);
And generating the URL only needs the additonal prefix key, plugin is optional if not used in plugin context:
$this->Html->link('Courses', [
'controller' => 'Courses',
'action' => 'index',
'plugin' => null,
'prefix' => 'student'
]);
See also
Cookbook > Routing > Prefix Routing
Cookbook > Routing > Plugin Routing
Cookbook > Routing > Routing File Extensions

Phalcon Routing for Admin controllers

I'm a newbie at Phalcon programming, I have admin/backend and frontend controllers
Admin will be served at '/admin/:controller/:action' and frontend will be served at '/:controller/:action'
Admin controllers (KalkuRitel\Controllers\Admin namespace) are located under
app/
controllers/
admin/
and frontend controllers (KalkuRitel\Controllers\Frontend namespace) are located under
app/
controllers/
frontend/
How do I accomplish this?
And how to serve 404 page within admin and frontend controllers with their own layout?
I would recommend to create modules
app/
modules/
admin/
...
frontend/
...
api/
...
register modules:
$application->registerModules(array(
'frontend' => array(
'className' => 'Application\Frontend\Module',
'path' => __DIR__ . '/../modules/frontend/Module.php'
),
'admin' => array(
'className' => 'Application\Admin\Module',
'path' => __DIR__ . '/../modules/admin/Module.php'
),
'api' => array(
'className' => 'Application\Api\Module',
'path' => __DIR__ . '/../modules/api/Module.php'
)
));
define properly Module.php files and than set route somewhat close to this:
use Phalcon\Mvc\Router as Router;
use Phalcon\CLI\Router as CliRouter;
/**
* Registering a router
*/
$di->setShared('router', function () use ($application, $config) {
if($application instanceof Phalcon\CLI\Console) {
return new CliRouter();
}
$router = new Router(false);
$router->setDefaultModule("frontend");
$router->setUriSource(\Phalcon\Mvc\Router::URI_SOURCE_GET_URL);
$router->removeExtraSlashes(TRUE);
foreach($application->getModules() as $key => $module) {
$prefix = $key == 'frontend' ? '' : ('/' . $key);
$router->add($prefix . '/:params', array(
'module' => $key,
'controller' => 'index',
'action' => 'index',
'params' => 1
))->setName($key);
$router->add($prefix . '/:controller/:params', array(
'module' => $key,
'controller' => 1,
'action' => 'index',
'params' => 2
));
$router->add($prefix . '/:controller/:action/:params', array(
'module' => $key,
'controller' => 1,
'action' => 2,
'params' => 3
));
}
return $router;
});
More in manual:
https://docs.phalconphp.com/pl/latest/reference/routing.html and
https://docs.phalconphp.com/pl/latest/reference/applications.html
The best way to accomplish this is to create a multiple module application.
You can learn more about multiple module application setups here:
https://docs.phalconphp.com/en/latest/reference/applications.html#multi-module
Once you have the structure for this in place you can set the routes something like this:
/*
* Dependency Injector
*/
$di = new \Phalcon\Di\FactoryDefault();
/**
* Register a router
*/
$di->setShared('router', function () {
$router = new \Phalcon\Mvc\Router();
$router->setDefaultModule('frontend');
$router->setDefaultNamespace('Multiple\Frontend\Controllers');
/*
* Frontend Routes
*/
$router->add('/:controller/:action', array(
'namespace' => 'Multiple\Frontend\Controllers',
'module' => 'frontend',
'controller' => 1,
'action' => 2
));
/*
* Backend Routes
*/
$backendRoutes = new \Phalcon\Mvc\Router\Group(array(
'namespace' => 'Multiple\Backend\Controllers',
'module' => 'backend'
));
$backendRoutes->setPrefix('/admin');
$backendRoutes->add('/:controller/:action', array(
'controller' => 1,
'action' => 3
));
$router->mount($backendRoutes);
return $router;
});
This is a quick answer and may require tweaking for your individual situation but should give you a good idea of how to accomplish your goal.

CakePHP - Controller::redirect and Auth->logoutRedirect not working

My CakePHP 2.5.3 app lives in a subdomain (domain/project_name) and apache rewrite rules are working correctly.
After I set App.fullBaseUrl='domain/project_name' in app/Config/core.php, Router::fullBaseUrl() works fine but, all the $this->Controller->redirect and all AuthComponent redirect to http://domain/project_name/project_name/controller/action.
Has anyone else encountered this and how did you fix it?
Many thanks in advance!
This is pattern for redirecting after log out:
// app/Controller/AppController.php
class AppController extends Controller {
//...
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array(
'controller' => 'posts',
'action' => 'index'
),
'logoutRedirect' => array( // <-- Let's focus at here.
'controller' => 'pages',
'action' => 'display',
'home'
),
'authenticate' => array(
'Form' => array(
'passwordHasher' => 'Blowfish'
)
)
)
);
public function beforeFilter() {
$this->Auth->allow('index', 'view');
}
//...
}
Source: http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html#authentication-login-and-logout
In your problem context, check logoutRedirect configuration array.
If you want handle redirecting by other ways:
public function logout() {
return $this->redirect($this->Auth->logout());
}
Source: http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html#authentication-login-and-logout

Phalcon route doesn't work

My phalcon app has worked fine with standard MVC route convention.
However, I want to handle some variable via URL, then I have a route:
$router = new \Phalcon\Mvc\Router();
$router->add("/timesheet/some/{year:[0-9]+}/{month:[0-9]{2}}/{day:[0-9]{2}}", "Timesheet::some");
$router->add("/timesheet/getreport/{type:[a-z]}/{year:[0-9]+}/{month:[0-9]{2}}/{day:[0-9]{2}}", "Timesheet::getreport");
$router->addPost("/user/auth", "User::auth");
return $router;
The first route (timesheet/some) worked fine, I can access to "year", "month" variable using $year = $this->dispatcher->getParam("year");, however the second route (timesheet/getreport) doesn't work. In this case, $year = $this->dispatcher->getParam("year"); return null.
If I changed to
$router = new \Phalcon\Mvc\Router(false);
$router->add("/:controller/:action", array(
"controller" => 1,
"action" => 2,
));
$router->add("/timesheet/some/{year:[0-9]+}/{month:[0-9]{2}}/{day:[0-9]{2}}", "Timesheet::some");
$router->addPost("/timesheet/getreport/{type:[a-z]}/{year:[0-9]+}/{month:[0-9]{2}}/{day:[0-9]{2}}", "Timesheet::getreport");
$router->addPost("/user/auth", "User::auth");
return $router;
every request will be routed to index/index. My project URL is localhost/fpas, and I already try both route /fpas/timesheet/some and /timesheet/some but it always redirect to index/index. What's wrong with it? (security/auth is commented out, so it's not result from authentication).
From my understand, the default route, $router = new \Phalcon\Mvc\Router(); only allow you to follow MVC convention, while $router = new \Phalcon\Mvc\Router(false); do but you have to specific all routes for every controller/action. Can I keep the convention for most of the action, while have specific rewrite routes for some action. How can I do that?
Thank you very much.
It works for me:
$router = new Phalcon\Mvc\Router();
$router->add("/", array(
'controller' => 'index',
'action' => 'setLanguage',
));
$router->add("/{language:[a-z]{2}}", array(
'controller' => 'index',
'action' => 'index',
'language' => 1
));
this one get's default routing just with language in the beginning
$router->add("/{language:[a-z]{2}}/:controller/:action", array(
'controller' => 2,
'action' => 3,
'language' => 1
));
with default action "index" when it's not in url
$router->add("/{language:[a-z]{2}}/:controller", array(
'controller' => 2,
'action' => 'index',
'language' => 1
));
some other routes
$router->add("/{language:[a-z]{2}}/:controller/:action/:params", array(
'controller' => 2,
'action' => 3,
'language' => 1,
'params' => 4
));
$router->add("/{language:[a-z]{2}}/question/add/{type}", array(
'language' => 1,
'controller' => 'question',
'action' => 'add',
));

ZF1 Routing Not working for View Script Sub-directories

I am using ZF1 and am trying to figure out why the view/scripts sub directories routing is not working. Here is the code from the bootstrap adding the routes. Please let me know what I may have wrong. Thanks for your time.
public function _initRoutes()
{
$controller = Zend_Controller_Front::getInstance();
$router = $controller->getRouter();
//Route for user Account
$account = new Zend_Controller_Router_Route(
'ecommerce/account/:action',
array(
'module' => 'ecommerce',
'controller' => 'user_account',
'action' => 'index'
)
);
//Route for user Cart
$cart = new Zend_Controller_Router_Route(
'ecommerce/cart/:action',
array(
'module' => 'ecommerce',
'controller' => 'user_cart',
'action' => 'index'
)
);
//die(print_r($account));
$router->addRoute('ecommerce/user_account/', $account);
$router->addRoute('ecommerce/user_cart/', $cart);
}
you have to try this code
$router = Zend_Controller_Front::getInstance();
$router1 = $router->getRouter();
$router1->addRoute('category/:id/:name/*',
new Zend_Controller_Router_Route('category/:user_id/:user_name/*', array(
'controller' => 'user',
'action' => 'index'
))
);
This will help you.

Categories