Dynamic key=>value segments in Zend Router - php

Need to achieve dynamic router param segmenting in Zend Router. The idea is:
have the url: /route/:route/resource/:resource/:identifier, with the following configuration:
'orchestration.rest.dynamic-router' => array(
'type' => 'Segment',
'options' => array(
'route' => '/route/:route/resource/:resource[/:identifier]',
'defaults' => array(
'controller' => 'Controller',
),
),
),
Need to make it support n-number different key=>value router params in the following format:
/route/:route/resource/:resource/:identifier/key1/value1/key2/value2/key3/value3
The second problem is that this should work only if you have the optional :identifier parameter provided.
This is what I've checked, but not sure how to achieve the goal:
https://docs.zendframework.com/zend-router/routing/#zend92router92http92segment

Leave static routes.
1) They are cached for better performance
2) if you use rest logic, use POST method, not GET(params in url)
the route
'orchestration.rest' => array(
'type' => 'Segment',
'options' => array(
'routerest' => '/routerest/:action',
'defaults' => array(
'controller' => 'Controller',
),
),
),
use post to consume rest action on server, with Ajax, or other...
(pseudo code)
datas={key1 : param1 , key2 : param2, etc...}
url=yourDomain/routerest/show (show=the action)
send Ajax Request(or something else in another langage with METHOD=POST)
other action like "getdatas"
... use post to consume rest action on server, with Ajax, or other...
datas={id1 : param1 , id2 : param2, etc...}
url=yourDomain/routerest/getdatas (getdatas=the action)
... in your Controller.php
...handle show action in route
function showAction() {
$request = $this->getRequest();
if ($request->isPost()) {
$param1=$this->params()->fromPost('key1','defaultvalue');
$param2=$this->params()->fromPost('key2','defaultvalue');
...
...
} else {... ERROR..}
}
...handle getdatas action in route
function getdatasAction() {
$request = $this->getRequest();
if ($request->isPost()) {
$id1=$this->params()->fromPost('id1','defaultvalue');
$id2=$this->params()->fromPost('id2','defaultvalue');
...
...
if ($id1$=='all') { return $this->redirect()->toRoute ('otherroute', array ('action' => 'xxx', 'paramxxx' => 'xx'));
...
...
} else {... ERROR..}
}

Related

Zend framework 2 routing required query parameters not working

I'm working on zf2 to make one of my routes only accessible when a query string parameter is passed. Otherwise, it will not. I've added a filter on the route section but when accessing the page without the query parameter, it is still going thru.
'router' => array(
'routes' => array(
'show_post' => array(
'type' => 'segment',
'options' => array(
'route' => '[/]show/post/:filter',
'constraints' => array(
'filter' => '[a-zA-Z0-9-.]*',
),
'defaults' => array(
'controller' => 'blog_controller',
'action' => 'show'
)
),
),
),
),
http://example.com/show/post/?postId=1235 = This should work
http://example.com/show/post?postId=1235 = This should work
http://example.com/show/post/ = This should not work
http://example.com/show/post = This should not work
The way you currently have this setup you would have to structure your url like this
http://example.com/show/post/anything?postId=1235
I think what you are wanting is to structure your route like this
'route' => '[/]show/post',
Not sure what you are trying to accomplish with [/] before show though, you are making that dash optional there?
I would write it like this
'route' => '/show/post[/:filter]',
This way you can structure your urls like this
http://example.com/show/post/anything?postId=1235
or
http://example.com/show/post?postId=1235
Then in your action you can access those parameters like this
$filter = $this->params('filter');
$post_id = $this->params()->fromQuery('post_id');
or just
$post_id = $this->params()->fromQuery('post_id');
***************UPDATE***************
It looks like zf2 used to include what you are trying to do and removed it because of security reasons.
http://framework.zend.com/security/advisory/ZF2013-01
Don't try to bend ZF2 standard classes to your way. Instead write your own route class, a decorator to the segment route, which will do exactly as you please:
<?php
namespace YourApp\Mvc\Router\Http;
use Zend\Mvc\Router\Http\Segment;
use use Zend\Mvc\Router\Exception;
use Zend\Stdlib\RequestInterface as Request;
class QueryStringRequired extends Segment
{
public static function factory($options = [])
{
if (!empty($options['string'])) {
throw new Exception\InvalidArgumentException('string parameter missing');
}
$object = parent::factory($options);
$this->options['string'] = $options['string'];
return $object;
}
public function match(Request $request, $pathOffset = null, array $options = [])
{
$match = parent::match($request, $pathOffset, $options);
if (null === $match) {
// no match, bail early
return null;
}
$uri = $request->getUri();
$path = $uri->getPath();
if (strpos($path, $this->options['string']) === null) {
// query string parametr not found in the url
// no match
return null;
}
// no query strings parameters found
// return the match
return $match;
}
}
This solution is very easy to unit test as well, it does not validate any OOP principles and is reusable.
Your new route definition would look like this now:
// route definition
'router' => array(
'routes' => array(
'show_post' => array(
'type' => YourApp\Mvc\Router\Http\QueryStringRequired::class,
'options' => array(
'string' => '?postId=',
'route' => '[/]show/post/:filter',
'constraints' => array(
'filter' => '[a-zA-Z0-9-.]*',
),
'defaults' => array(
'controller' => 'blog_controller',
'action' => 'show'
)
),
),
),
),

ZF2 Create route like " login?url=foo "

I'm struggling on this for 2 hours now. I've managed to create a route with parameter (named url) like /login/url:
'login' => array(
'type' => 'segment',
'options' => array(
'route' => '/login[/:url]',
'defaults' => array(
'controller' => 'my_controller',
'action' => 'login',
),
),
),
However I'd like to have an URL which looks like /login?url=foo. I've tried something like:
'route' => '/login[?url=:url]',
But it does not work. Any idea how to achieve this on Zend Framework 2 ?
Thanks a lot!
EDIT:
Trying something else like:
// onBootstrap method --> redirect to login page with request url as param
$url = $router->assemble(
array('url', $e->getRequest()->getRequestUri()),
array('name' => 'login')
);
In controller (login action):
$request = $this->getRequest();
var_dump($request); exit;
I don't see the requested URL anywhere... any suggestion?
I don't think you should put your query string segment in your route. It would seem reasonable to have your route to be just /login and then manage your query string parameter in the controller.
Otherwise, but I don't recommend it since it is deprecated, you could try to use the Query router.

Is it posible to create a urlManager Rule which preloads an object based on ID?

Working with Yii 2.0.4, I'm trying to use urlManager Rule to preload an object based on a given ID in the URL.
config/web.php
'components' => [
'urlManager' => [
[
'pattern' => 'view/<id:\d+>',
'route' => 'site/view',
'defaults' => ['client' => Client::findOne($id)],
],
[
'pattern' => 'update/<id:\d+>',
'route' => 'site/update',
'defaults' => ['client' => Client::findOne($id)],
],
]
]
If this works, it will not be necessary to manually find and object each time, for some CRUD actions:
class SiteController extends Controller {
public function actionView() {
// Using the $client from the urlManager Rule
// Instead of using $client = Client::findOne($id);
return $this->render('view', ['client' => $client]);
}
public function actionUpdate() {
// Using $client from urlManager Rule
// Instead of using $client = Client::findOne($id);
if ($client->load(Yii::$app->request->post()) && $client->save()) {
return $this->redirect(['view', 'id' => $client->id]);
} else {
return $this->render('edit', ['client' => $client]);
}
}
}
NOTE: The above snippets are not working. They're the idea of what I want to get
Is it possible? Is there any way to achieve this?
If you look closer: nothing actually changes. You still call Client::findOne($id); but now doing it in an unexpected and inappropriate place, and if you look at the comment about default parameter it says:
array the default GET parameters (name => value) that this rule provides.
When this rule is used to parse the incoming request, the values declared in this property will be injected into $_GET.
default parameter is needed when you want to specify some $_GET parameters for your rule. E.g.
[
'pattern' => '/',
'route' => 'article/view',
'defaults' => ['id' => 1],
]
Here we specify article with id = 1 as default article when you open main page of site e.g. http://example.com/ will be handled as http://example.com/article/view?id=1
I can suggest to you add property clientModel in to your controller and then in beforeAction() method check if its update or view action then set
$this->clientModel = Client::findOne($id);
and in your action:
return $this->render('view', ['client' => $this->clientModel]);

Passing options to php script using ZF2 framework

My application uses Zend Framework 2 and I am trying to pass some options to it when ran via command line:
php index.php generate --date="2015-01-01"
However I am getting the error: Invalid arguments or no arguments provided
My controller looks like:
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class GenerateController extends AbstractActionController
{
public function indexAction()
{
$longopts = array(
'date::',
);
$opts = getopt('', $longopts);
if (isset($opts['date'])) {
$date = $opts['date'];
} else {
$date = date('Y-m-d');
}
var_dump($date);
die();
}
}
I would like the var_dump to show the date provided in the options or today's date. The script runs but just gives the above error. Any help is greatly appreciated.
My module.config.php is functioning correctly:
// Placeholder for console routes
'console' => array(
'router' => array(
'routes' => array(
'get-happen-use' => array(
'options' => array(
//php index.php get happen --verbose apache2
// add [ and ] if optional ( ex : [<doname>] )
'route' => 'generate',
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'generate',
'action' => 'index'
),
),
),
)
)
),
You need to define your console params or flags in route. According documentation, your route definition should looks like
'route' => 'generate [--date=]',
for optional value flag date, or if flag date is mandatory:
'route' => 'generate --date=',
Then you can access value of this flag in controller from request (documentation):
$date = $this->getRequest()->getParam('date', null); // default null

Kohana 3.2 - Routing questions

Firstly, Kohana's documentation is terrible, before people go "read the docs" I have read the docs and they don't seem to make much sense, even copying and pasting some of the code doesn't work for some things in the documentation.
With that in mind, I have a route like so:
//(enables the user to view the profile / photos / blog, default is profile)
Route::set('profile', '<userid>(/<action>)(/)', array( // (/) for trailing slash
"userid" => "[a-zA-Z0-9_]+",
"action" => "(photos|blog)"
))->defaults(array(
'controller' => 'profile',
'action' => 'view'
))
This enables me to go http://example.com/username and be taken to the users profile, http://example.com/username/photos to be taken to view the users photos and http://example.com/username/blog to view the blog.
If somebody goes http://example.com/username/something_else I want it to default to the action view for the user specified in <userid> but I can't seem to find any way of doing this.
I could do it like this:
Route::set('profile', '<userid>(/<useraction>)(/)', array(
"userid" => "[a-zA-Z0-9_]+",
"useraction" => "(photos|blog)"
))->defaults(array(
'controller' => 'profile',
'action' => 'index'
))
then in the controller do this:
public function action_index(){
$method = $this->request->param('useraction');
if ($method && method_exists($this, "action_{$method}")) {
$this->{"action_{$method}"}();
} else if ($method) {
// redirect to remove erroneous method from url
} else {
$this->action_view(); // view profile
}
}
(it might be better in the __construct() function but you get the gist of it.)
I'd rather not do that though if there is a better method available (which there really should be)
I think the answer might be in the regex but the following does not work:
$profile_functions = "blog|images";
//(enables the user to view the images / blog)
Route::set('profile', '<id>/<action>(/)', array(
"id" => "[a-zA-Z0-9_]+",
"action" => "($profile_functions)",
))->defaults(array(
'controller' => 'profile'
));
Route::set('profile_2', '<id>(<useraction>)', array(
"id" => "[a-zA-Z0-9_]+",
"useraction" => "(?!({$profile_functions}))",
))->defaults(array(
'controller' => 'profile',
'action' => 'view'
));
although it does match when nothing is after the ID.
I would set up the route like this:
Route::set('profile', '<userid>(/<action>)(/)', array(
"userid" => "[a-zA-Z0-9_]+",
"action" => "[a-zA-Z]+"
))->defaults(array(
'controller' => 'profile',
'action' => 'index'
))
And then in the controllers before() method:
if(!in_array($this->request->_action, array('photos', 'blog', 'index')){
$this->request->_action = 'view';
}
Or somethig similiar, just validate the action in the controller...
EDIT:
This could also work:
if(!is_callable(array($this, 'action_' . $this->request->_action))){
$this->request->_action = 'view';
}

Categories