Jump parameter in function - php

I have a controller in codeigniter called 'Main' with this function:
public function index ($id = false, $filter ='htmlentities') {
...
...
}
I want to call it through the URI 'jumping' the first parameter so that it remains 'false':
I would like to be able through the URI using something like:
'main/index/false/myfilter'
However this doesn't work, does anyone know how can I 'jump' this first parameter so that its value remains being false but i am able to change the filter?
(changing parameter order in function is NOT an option)

Just test for the string 'false' at the top of the controller method:
public function index ($id = false, $filter ='htmlentities') {
if ($id == 'false') {
$id = false;
}
// ...
}
Another possibility might be to use a custom route and simply discard the first parameter. In your app/config/routes.php file, add the rule:
$route['main/index/:filter'] = 'main/index/false/$1';
Now, when you visit 'main/index/myfilter', the $id parameter will be set to false (a string, not a boolean!)

Related

How to inform only the first and the last arguments of a function?

How may I use this function and inform only the first and the last arguments?
Function
function foo($first = false, $second = false, $third = false, $last = false)
{
if($first && $last)
{
echo 'ok';
}
}
I've tried the code below, but it didn't work...
foo($first = true, $last = true);
PHP doesn't do named arguments as python does. See this question for more info.
However, life can be made easier by using other techniques like...
Modify the signature of the function to accept arguments as an associative array
Function
function foo($parameters)
{
// Provide default values if parameters are not specified
$first = isset($parameters['first']) ? $parameters['first'] : false;
$second = isset($parameters['second']) ? $parameters['second'] : false;
$third = isset($parameters['third']) ? $parameters['third'] : false;
$last = isset($parameters['last']) ? $parameters['last'] : false;
if($first && $last)
{
echo 'ok';
}
}
Call
foo(['first' => true, 'last' => true]);
This way is suitable when you have a number of parameters big and variative enough and you have a complex logic inside the function so that writing all this code pays off.
It is not very convenient, however, because the default values are specified not in an obvious way, there's extra code and it's hard to track parameter usages.
Modify the signature of the function to accept a parameter object which holds all the necessary info
This is the way to go for complex signatures and especially if you have a cascade of methods which use the same arguments. I love it because it solved a big problem with passing up to 10 query parameters through processing pipeline. Now it's just one object with possibility to find every parameter usage and friendly autosuggestion of available parameters when typing ->.
Parameter object class
class ParameterObject
{
public $first = false;
public $second = false;
public $third = false;
public $last = false;
}
Function
function foo(ParameterObject $paramObj)
{
if($paramObj->first && $paramObj->last)
{
echo 'ok';
}
}
Call
$paramObj = new ParameterObject();
$paramObj->first = true;
$paramObj->last = true;
foo($paramObj);
Note! You can modify the object to use method for setting parameters which will provide you with possibility of chaining if you return $this in every set method. So the function call would like like this:
$paramObj = new ParameterObject();
foo($paramObj->setFirst(true)->setSecond(true));
maybe
foo(true, false, false, true);
or change the position of arguments like
function foo($first, $last, $second=false, $third=false)
foo(true, true);
?
if you want to use last argument of function in php you must enter all argument before it and you can't use name of arguments when call functions. in some language like swift can call function with name of argument but not in php

replace a wildcard for url comparison

I need to check valid routes from a route files where i want to put a wildcard (or placeholder) for url part that is dynamic.
The router read all routes in that json format:
{"action" : "BlogController#showPost", "method" : "GET", "url" : "showPost/id/{}"}
I need when the comparsion occurs to change the holder {any} with the current value and maybe allow to put regex expression inside the {any} tag.
An url like this:
showPost/id/211 have to be compared with showPost/id/{} and should return true. If possible i would like to allow putting {'[0-9]\'} as optional param to ensure that the real value match a regex expression.
What best solution to do this?
The comparsison method is this:
public static function findAction($query) {
foreach (Router::getInstance()->routes as $route) {
if ($route->url == $query) {
return $route;
}
}
}
The $query contains /showPost/id/221 and the Router::getInstance()->routes->route->url contains showPost/id/{}
The post is related to this auto-solved question:
how to make nice rewrited urls from a router
I don't re-post router code in order to avoid duplication.
Thanks in advance
I found a solution using "?" as a wildcard for routes json file. Its not maybe the best way but actually works.
The method now replace (and try to check) the real path queries with ? and check the routes each cycle.
public static function findAction($query) {
//d($query);
$queryArray = explode("/", $query);
//d($queryArray);
foreach (Router::getInstance()->routes as $route) {
if ($route->url == $query) {
// replace current routes url with incoming url
$route->url = $query;
return $route;
} else {
$queryReplace = null;
foreach ($queryArray as $key => $value) {
if (strpos($route->url,"?")) {
$queryReplace = str_replace("?", $value, $route->url);
if($queryReplace == $query) {
$route->url = $query;
return $route;
}
}
}
}
I still would like to put {any or regex} but atm i did not found a solution to this.

Laravel 5.1 specifing current page for pagination

Been working on this for far too long with no results. I have tried.
`\Illuminate\Pagination\Paginator::setCurrentPage($current_page);`
returns
Call to protected method Illuminate\Pagination\Paginator::setCurrentPage()
\Paginator::setCurrentPage($current_page);
returns Call to protected method Illuminate\Pagination\Paginator::setCurrentPage()
\DB::getPaginator()->setCurrentPage($current_page);
returns call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'getPaginator'
$tmp = new Post( ); $tmp->getConnection()->setCurrentPage($current_page);
returns call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'getPaginator'
How can I specify the page? I need to specify it manually.
I had hoped it to be as easy as $model->find( )->paginate($per_page, $page)
The Builder Class has:
public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
You can call
Model::find(...)->paginate($per_page, ['*'], 'page', $page);
Suppose you have $users to paginate in your UserController, you might do:
public function index()
{
$currentPage = 3; // You can set this to any page you want to paginate to
// Make sure that you call the static method currentPageResolver()
// before querying users
Paginator::currentPageResolver(function () use ($currentPage) {
return $currentPage;
});
$users = \App\User::paginate(5);
return view('user.index', compact('users'));
}
I believe this applies to Laravel 5.0 and above. Have to check on that.
for those people who using api and they want to specify the current page in api, they can use extra parameter like this:
getProducts?page=3

CodeIgniter - Optional parameters

I'm building my first CodeIgniter application and I need to make URLs like follows:
controllername/{uf}/{city}
Example: /rj/rio-de-janeiro
This example should give me 2 parameters: $uf ('rj') and $city ('rio-de-janeiro')
Another URL possible is:
controllername/{uf}/{page}
Example: /rj/3
This example should give me 2 parameters: $uf ('rj') and $page (3)
In other words, the parameters "city" and "page" are optionals.
I can't pass something like '/uf/city/page'. I need always or 'city' OR 'page'.
But I don't know how to configure these routes in CodeIgniter configuration to point to same method (or even to different methods).
I've found the correct result:
$route['controllername/(:any)/(:any)/(:num)'] = 'ddd/index/$1/$2/$3';
$route['controllername/(:any)/(:num)'] = 'ddd/index/$1/null/$2'; // try 'null' or '0' (zero)
$route['controllername/(:any)'] = 'ddd/index/$1';
The Index method (inside "ControllerName") should be:
public function Index($uf = '', $slug = '', $pag = 0)
{
// some code...
if (intval($pag) > 0)
{
// pagination
}
if (!empty($slug))
{
// slug manipulation
}
}
Hope it helps someone.
Thank you all.
public function my_test_function($not_optional_param, $optional_param = NULL)
{
//do your stuff here
}
have you tried this?
For example, let’s say you have a URI like this:
example.com/index.php/mycontroller/myfunction/hello/world
example.com/index.php/mycontroller/myfunction/hello
Your method will be passed URI segments 3 and 4 (“hello” and “world”):
class MyController extends CI_Controller {
public function myFunction($notOptional, $optional = NULL)
{
echo $notOptional; // will return 'hello'.
echo $optional; // will return 'world' using the 1st URI and 'NULL' using the 2nd.
}
}
Reference: https://codeigniter.com/user_guide/general/controllers.html

Can I use a function to return a default param in php?

I would like to do something like this:
function readUser($aUser = loadDefaultUser()){
//doing read User
}
I find that it will display a error to me, how can I pass a function return as a default value? Thank you.
I would rather give a Null value for this argument and then call loadDefaultUser() in the body of the function. Something like this:
function readUser($aUser = NULL){
if(is_null($aUser)){
$aUser = loadDefaultUser();
}
//...
}
Yes, you can provide a default argument. However, the default argument "must be a constant expression, not (for example) a variable, a class member or a function call."
You can fake this behaviour by using some constant value for the default, then replacing it with the results of a function call when the function is invoked.
We'll use NULL, since that's a pretty typical "no value" value:
function readUser($aUser = NULL) {
if (is_null($aUser))
$aUser = loadDefaultUser();
// ... your code here
}
You can add a callback-parameter to your loadDefaultUser() function when it's finished it fires the callback function with the return/result. It's a bit like ajax-javascript callbacks.
function loadDefaultUser ( $callback )
{
$result = true;
return $callback($result);
}
function readUser($aUser = NULL){
if ($aUser === NULL){
$aUser = loadDefaultUser();
}
//do your stuff
}

Categories