I'm trying to internationalize all the pages on my CakePHP site with the following format:
/en/about
/zh/about (for Chinese version)
etc.
I already have all the routes defined at router.php, eg.
Router::connect('/about/*', array('controller' => 'pages', 'action' => 'about'));
Router::connect('/login/*', array('controller' => 'users', 'action' => 'login'));
// etc...
How do I make it so that /language/ prefix is automatically applied to all the Router::connect()s?
At CakePHP library's router.php, there is an example for the similar routing and is given as such:
Router::connect('/:lang/:controller/:action/:id',
array(), array('id' => '[0-9]+', 'lang' => '[a-z]{2}'));
This however, only works for the default routing type (eg. /pages/about/) and not a specially defined one like /about for my example.
In other words, it would work when user visits /zh/pages/about but not when user visits /zh/about
Any suggestions or do I have to manually rewrite all my Router::connect()s to include lang?
Try this:
Router::connect('/:lang/:controller', array(), array('lang' => '[a-z]{2}'));
Router::connect('/:lang/:controller/:action', array(), array('lang' => '[a-z]{2}'));
Router::connect('/:lang/:controller/:action/*', array(), array('lang' => '[a-z]{2}'));
Related
I have a website made in PHP Phalcon, and it has several controllers.
Now I need this website to receive words in the URL (example.com/WORD) and check if they exist in the database, but I must continue to support other controllers like example.com/aboutme.
After few hours of trying different methods and searching online I cannot find a way to accomplish this task. The closer intent was creating a Route to redirect non-existing actions to a new controller, but I cannot make this solution work.
Can you think on a solution that may work and share the code/idea? I am not adding any code because I could not get to do anything useful.
This should not be a problem at all. Here are sample routes:
// Default - This serves as multipurpose route definition
// I can use it to create non pretty urls if I don't want to define them.
// Example: profiles/login, profiles/register - Don't need those pretty :)
$router->add('/:controller/:action/:params', ['controller' => 1, 'action' => 2, 'params' => 3]);
$router->add('/:controller/:action', ['controller' => 1, 'action' => 2]);
$router->add('/:controller', ['controller' => 1]);
// Product page - www.example.com/product-slug-here
$router->add('/{slug}', 'Products::view')->setName('product');
// Blog
$router->add('/blog/{slug}', 'Blog::view')->setName('blog');
$router->add('/blog', 'Blog::index')->setName('blog-short');
// Contacts - Pretty urls in native website language
$router->add('/kontakti', 'Blabla::contacts')->setName('contats');
After all, rules did not worked, so I came out with a workaround. I am catching the the exception raised when a controller don't exist and running my code there. So far the only issue is the bitter taste of contributing to spaghetti code :-(
try{
$application = new Application($di);
echo $application->handle()->getContent();
}
catch(\Phalcon\Mvc\Dispatcher\Exception $e)
{
$word = substr($e->getMessage(), 0, strpos($e->getMessage(), "Controller"));
// RUN ESPECIFIC CODE HERE
}
I see that the question is very old, but I found it while searching for a solution to the same problem, and what worked for me is adding the '/' for the controllers route:
// Page Not Found - 404
$router->notFound(
[
'controller' => 'index',
'action' => 'pageNotFound',
]
);
// Blog page - www.example.com/blog-slug-here
$router->add(
'/{slug}',
[
'controller' => 'BlogPost',
'action' => 'index',
]
)->setName('Blog-post');
$router->add('/:controller/:action/:params',
[
'controller' => 1,
'action' => 2,
'params' => 3
]
);
$router->add('/:controller/:action',
[
'controller' => 1,
'action' => 2
]
);
$router->add('/:controller/',
[
'controller' => 1
]
);
$router->add(
'/',
[
'controller' => 'index',
'action' => 'index',
]
);
This way I can have a blog post URL like www.example.com/admin and an admin area as www.example.com/admin/
Recently, I've been studying cake, I've seen the auth library which said to be will take care of the access control over your app, but, it seems like, you can't initialize or even use this auth library when you're not in the 'UsersController', i did not want that, what if it has some admin part wherein i want the URI to be admin/login, or just simply /login, i've been scratching my head over this one, please help.
Another question, why it seems like the functionality of the '$this->redirect' is not effective when i'm putting this one at any method that contains nothing but redirection, or even in the __construct()?
thanks guys, hoping someone could clearly explain to me those things.
you can use the Auth component inside any controller in the application. If you want it will only effect with the admin section then you can add condition in the beforeFilter funciton in you application AppController on Auth initialization like.
// for component initialization.
public $components = array(
'Auth' => array(
'authenticate' => array(
'userModel' => 'Customer', // you can also specify the differnt model instead of user
'Form' => array(
'fields' => array('username' => 'email')
)
)
)
}
and you can bind this on the admin routing like
function beforeFilter(){
// only works with admin routing.
if(isset($this->request->params['prefix']) && ($this->request->params['prefix'] == 'admin')){
$this->Auth->loginRedirect = array('admin' => true, 'controller' => 'pages', 'action' => 'index');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login', 'admin' => true);
$this->Auth->loginAction = array('admin' => true, 'controller' => 'customers', 'action' => 'login');
}
}
If you're using cake 2.3.x or later then make sure you have specified the redirect action in correct format like.
return $this->redirect('action_name'); // you can also specify the array of parameters.
I obviously have a fundamental misunderstanding of how pagination works in CakePHP.
I have the following route set up which shows all posts in a category:
Router::connect('/:parent/:category',
array('controller' => 'posts', 'action' => 'viewCategory'),
array('parent' => '[a-z0-9-]+', 'category' => '[a-z0-9-]+'));
The pages work fine, however the pagination helper is outputting the wrong links for pagination.
I'm using $this->Paginator->numbers().
It's outputting links in this format: mysite.com/posts/viewCategory?page=2
rather than like this: mysite.com/parent-category/sub-category?page=2.
I've tried adding the following route after the first one and it still doesn't work:
Router::connect('/:parent/:category/:page',
array('controller' => 'posts', 'action' => 'viewCategory'),
array('parent' => '[a-z0-9-]+',
'category' => '[a-z0-9-]+',
'page' => '[0-9]+'));
For reference, my pagination options set in my view are as so:
<?php $this->Paginator->options(
array('url' =>
array('controller' => 'posts', 'action' => 'viewCategory')
)); ?>
What am I doing wrong here?
You are setting the url yourself
This is your paginator options call:
<?php
$this->Paginator->options(array(
'url' => array(
'controller' => 'posts',
'action' => 'viewCategory'
)
));
?>
Where you are overriding the current url - and explicitly requesting that the paginator uses the the '/posts/viewCategory' url (with no arguments) as it's base url.
Just don't define the url
Simply don't call options and the helper will use the current url - that should mean that if the current url is:
/parent-category/sub-category
Then page 2 will be (assuming you are using the paramType option to use GET arguments rather than named parameters):
/parent-category/sub-category?page=2
If that's not the case there's information missing from the question; it's important to distinguish between "vanity routes not being used" and "the url is not equivalent (the current situation).
Just had a battle fixing something similar and came across this post. Though old, but I think my answer might save someone the time I had to spend fixing it.
Basically, what you need to do is call the Paginator->options() before Paginator->numbers(), thus:
$this->Paginator->options(
array(
'controller' => 'parent-category',
'action' => 'sub-category'
)
);
Though the controller and action do not exist, it just tricks CakePHP to use them "AS IS", since the reverse routing isn't working!
And for those (like me), who want have set up a route similar to
Router::connect(
'/go/page:id',
array(
'controller' => 'blog',
'action' => 'paginated'
)
);
There might be difficulty setting up the Paginator options. This, however, worked for me:
$this->Paginator->options(
array(
'controller' => 'go',
'action' => '/'
)
);
I guess you know why it worked ;)
My link:
echo $link->link($planDetailsByCompany['PlanDetail']['name'],
array('controller' => 'plan_details', 'action' => 'view_benefit_schedule',
'id' => $planDetailsByCompany['PlanDetail']['id'],
'slug' => $planDetailsByCompany['PlanDetail']['name']));
My custom route:
Router::connect('/pd/:id-:slug',
array('controller' => 'plan_details', 'action' => 'view_benefit_schedule'),
array('pass' => array('id', 'slug'),
'id' => '[0-9]+'));
My url is displaying like so:
..pd/44-Primary%20Indemnity
I cannot determine how to remove the %20 and replace it with a "-". There is a space in the company name that is causing this. Is this possible within the CakePHP router functionality? If so, how? Or another method.
Geeze.. I just solved this!
In my link above, replace the 'slug' line with:
...'slug' => Inflector::slug($planDetailsByCompany['PlanDetail']['name'])...
The Inflector handles the spaces in the url. And my result url is:
...pd/44-Primary_Indemnity
Is it possible in CakePHP to have URL aliases in routes.php? Or by what other means can achieve something equivalent:
Lets assume I have some paginated views. Among the possible orderings there are particular ones I want to bind to a simple URL. E.g.:
http://example.com/headlines => http://example.com/posts/listView/page:1/sort:Post.created/direction:desc
http://example.com/hottopics => http://example.com/posts/listView/page:1/sort:Post.view_count/direction:desc etc.
How do I add parameters to a Router::connect()? Pseudo code:
Router::connect('/'.__('headlines',true),
array(
'controller' => 'posts',
'action' => 'listView'
'params' => 'page:1/sort:Post.created/direction:desc',
)
);
Note that the Router "translates" a URL into Controllers, Actions and Params, it doesn't "forward" URLs to other URLs. As such, write it like this:
Router::connect('/headlines',
array(
'controller' => 'posts',
'action' => 'listView'
'page' => 1,
'sort' => 'Post.created',
'direction' => 'desc'
)
);
I don't think '/'.__('headlines', true) would work, since the app is not sufficiently set up at this point to translate anything, so you'd only always get the word in your default language back. Also, you couldn't switch the language anymore after this point, the first use of __() locks the language.
You would need to connect all URLs explictly. To save you some typing, you could do this:
$headlines = array('en' => 'headlines', 'de' => 'schlagzeilen', ...);
foreach ($headlines as $lang => $headline) {
Router::connect("/$headline", array('controller' => ..., 'lang' => $lang));
}
That will create a $this->param['named']['lang'] variable, which you should use in the URL anyway.
Yes, it is possible... Bootstrap.php loads before routes so if you set there something like:
session_start();
if(isset($_SESSION['lng'])){
Configure::write('Config.language', $_SESSION['lng']);
}
...and in your app controller in beforeFilter:
$language = 'xy';
Configure::write('Config.language', $language);
$_SESSION['lng'] = $language;
So initial page render you prompt for language, redirect to xy.site.com or www.site.com/xy whatever you prefer. Now second render will change $language and on page links and set $_SESSION['lang']...
All router links like:
Router::connect(__('/:gender/search/:looking_for/*'), array('controller' => 'users', 'action' => 'search'));
will become:
Router::connect(__('/:gender/trazi/:looking_for/*'), array('controller' => 'users', 'action' => 'search'));
or:
Router::connect(__('/:gender/suche/:looking_for/*'), array('controller' => 'users', 'action' => 'search'));
100% tested, works in CakePHP 2.2. Also further improvement is possible if you put subdomain/language url parser in the bootstrap itself...