I have a method
function checkin($var1){
$newVar1 = $var1;
....
...
}
I am calling it via Restful and I am passing it like this
$url = 'http://mydomain.com/controller/checkin/'.$var1;
Now i want to pass two variables but I am not sure how would it pick the second one
I guess I can do this
$url = 'http://mydomain.com/controller/checkin/'.$var1.'/'.$var2;
not sure what would I do on receiving end to make sure it knows what var to use where.
thanks
On the other end, you have to change your action method signature to
function checkin($var1, $var2){
// (...)
}
Another option is using Cake's named parameters. That would require a change in both the url and the action:
URL
$url = 'http://mydomain.com/controller/checkin/var1:'.$var1.'/var2:'.$var2;
Action method
function checkin(){
$var1 = $this->params['named']['var1'];
$var2 = $this->params['named']['var2'];
}
Related
I'm creating an API with PHP and am having difficulty with the URL, it gets this URL to me http://localhost/api/index/Peoples/3
The idea is that I want to use the Peoples Class and I want to get the Person with code 3, is there any way I can get Peoples and number 3?
The idea I made was this, I retrieve the URL from the browser and I'm going to explode on it. While I do not need to pass parameters through the url this works perfectly
public function getClass(){
$params = explode("/api/index/", $this->currentUrl);
if(count($params) == 1)
return "no have class !";
else
{
$params = explode('/', $params[1]);
$this->callClass($params[0]);
return "Classe : ".$params[0];
}
}
with this code I can recover Peoples and then know which class I will use. now I want to pass the parameter of the code, as for example 3. I could pass as follows ../Peoples?id=3 but I would have to break even more my string, have a better way to do this?
What's the difference between passing ../Peoples?id=3 or ../Peoples/3 and how can I recover?
you can try something like this
public function getClass()
{
$path = explode('/', parse_url($this->currentUrl, PHP_URL_PATH));
if(count($path) !== 5){
return 'not valid url';
}
$id = array_pop($path);
$class = array_pop($path);
//$this->callClass($class);
$newPath = $class.'?id='.$id;
return $newPath;
}
and regarding your question about /Peoples?id=3 or ../Peoples/3
the second one is easier if you are working with a framework such as symfony or laravel where you can define controllers and the first one you can easily fetch you data from the URL with $_GET['id']
Hope that was what you are looking for.
ok, I have a url that calls a webservice, lets say that url is:
http://url.com/products/[productid]?Lanaugae=english$username=username&token=1234
What I'm doing is calling the webservice inside a function, grab the product ID from a get and pass it in and then fire off the function that does all the curl goodness.
The troublesome bit is the productid is in the middle of the url, which I declared globally, and the curl bit fires from another function. I think in .net you could say {0} in the place of [productid] then when you call the variable tell it what should go into [productid], can I do something similar in PHP?
So at the top of my class I want:
$this->url = 'http://url.com/products/{0}?Lanaugae=engish$username=username&token=1234';
this in my function I want to do something like:
$productid = $_GET["productid"];
$responseData = $this->curl_dat_thing($this->url, $productid);
...This possible/make sense?
Try using sprintf() like this:
$this->url = 'http://url.com/products/%s?Lanaugae=engish$username=username&token=1234';
$productid = $_GET["productid"];
$responseData = $this->curl_dat_thing(sprintf($this->url, $productid));
I'm not sure what's inside curl_dat_thing() but you should do this:
$this->url = 'http://url.com/products/'.$productid.'?Lanaugae=engish&username=username&token=1234';
Example:
...scms/contracts/set_pm/3/Monthly
this is the URL and i want to get the word monthly...I cant use uri->segment in my view so I'm asking if there's other way
Just retrieve the current_url() and explode it with /, but why do such cumbersome process when you have lots of options provided by CI.
If you cant use $this->uri in your view just put that segment in a variable and load the view like this:
$data['segment'] = $this->uri->segment(5); //your segment here you want in your view
$this->load->view('view', $data);
Now, you will get the segment in your view as $segment.
May be something like this
$actual_link = current_url();
$slashes = explode("/",$actual_link);
echo $element = $slashes[count($slashes)-1];
You can use explod function in PHP to get a tab with your string in input.
$tab = explode("/", $url);
$last = end($tab);
Considering contracts is your controller file name and set_pm is your function then you can also fetch it like this:
class Contracts extends CI_Controller {
function set_pm($id, $interval)
{
echo $id; //prints 3
echo $interval; // prints Monthly
}
}
I'm writing a unit testing platform and I want to be able to dynamically generate a function based off of each function in the web service I am testing. The dynamic function would be generated with default(correct) values for each argument in the web service and allow them to be easily traded out with incorrect values for error testing.
$arrayOfDefVals = array(123, 'foo');
testFunctionGenerator('function1', $arrayOfDefVals);
//resulting php code:
function1Test($expectedOutput, $arg1=123, $arg2='foo')
{
try
{
$out = function1($arg1, $arg2);
if($expectedOutput === $out)
return true;
else
return $out;
}
catch ($e)
{
return $e;
}
}
This would allow me to quickly and cleanly pass one bad argument, or any number of bad arguments, at a time to test all of the error catching in the web service.
My main question is:
Is this even possible with php?
If it's not possible, is there an alternative?
EDIT: I'm not looking for a unit test, I'm trying to learn by doing. I'm not looking for advice on this code example, it's just a quick example of what I would like to do. I just want to know if it's possible.
I would not try that first as PHP has not build-in macro support. But probably something in that direction:
function function1($param1, $param2)
{
return sprintf("param1: %d, param2: '%s'\n", $param1, $param2);
}
/* Macro: basically a port of your macro as a function */
$testFunctionGenerator = function($callback, array $defVals = array())
{
$defVals = array_values($defVals); // list, not hash
return function() use ($callback, $defVals)
{
$callArgs = func_get_args();
$expectedOutput = array_shift($callArgs);
$callArgs += $defVals;
return $expectedOutput == call_user_func_array($callback, $callArgs);
};
};
/* Use */
$arrayOfDefVals = array(123, 'foo');
$function1Test = $testFunctionGenerator('function1', $arrayOfDefVals);
var_dump($function1Test("param1: 456, param2: 'foo'\n", 456)); # bool(true)
Probably this is helpful, see Anonymous functionsDocs, func_get_argsDocs, the Union array operatorDocs and call_user_func_arrayDocs.
Well, for starters, you can set default parameters in functions:
function function1Test($expectedOutput, $testArg1=123, $testArg2='foo') {
...
}
Beyond that, I'm not really sure what you're trying to achieve with this "function generator"...
Read about call_user_func and func_get_args
This example from the manual should get you on the right track:
<?php
call_user_func(function($arg) { print "[$arg]\n"; }, 'test'); /* As of PHP 5.3.0 */
?>
If it's a function you have file access to (i.e., it's not a part of the PHP standard library and you have permissions to read from the file), you could do something like this:
Assume we have a function like this located in some file. The file will have to be included (i.e., the function will have to be in PHP's internal symbol table):
function my_original_function($param1, $param2)
{
echo "$param1 $param2 \n";
}
Use the ReflectionFunction class to get details about that function and where it's defined: http://us2.php.net/manual/en/class.reflectionfunction.php.
$reflection = new ReflectionFunction('my_original_function');
Next, you can use the reflection instance to get the path to that file, the first/last line number of the function, and the parameters to the function:
$file_path = $reflection->getFileName();
$start_line = $reflection->getStartLine();
$end_line = $reflection->getEndLine();
$params = $reflection->getParameters();
Using these, you could:
read the function out of the file into a string
rewrite the first line to change the function name, using the known function name as a reference
rewrite the first line to alter the parameter defaults, using $params as a reference
write the altered function string to a file
include the file
Voila! You now have the new function available.
Depending on what it is you're actually trying to accomplish, you could also potentially just use ReflectionFunction::getClosure() to get an closure copy of the function, assign it to whatever variable you want, and define the parameters there. See: http://us.php.net/manual/en/functions.anonymous.php. Or you could instantiate multiple ReflectionFunctions and call ReflectionFunction::invoke()/invokeArgs() with the parameter set you want. See: http://us2.php.net/manual/en/reflectionfunction.invokeargs.php or http://us2.php.net/manual/en/reflectionfunction.invoke.php
i am using http://www.asual.com/jquery/address/ plugin and trying to parse some url, this is what i got:
<script>$(function(){
$.address.init(function(event) {
// Initializes the plugin
$('a').address();
}).change(function(event) {
$('a').attr('href').replace(/^#/, '');
$.ajax({
url: 'items.php',
data:"data="+event.value,
success: function(data) {
$('div#content').html(data)
}
})
});
})</script>
then HTML:
link02
link03
then im calling item.php, wich for now only has
echo $_GET["data"];
so after the ajax request has complete it echoes :
/items.php?id=2
/items.php?id=3
how can i parse this so i get only the var values? it is better to do it on client side?
and also if my html href is something like link02
jQuery address will ignore the &var=jj
cheers
You can use parse_url() to get the query string and then parse_str to get the query string parsed into variables.
Example:
<?php
// this is your url
$url = 'items.php?id=2&var=jj';
// you ask parse_url to parse the url and return you only the query string from it
$queryString = parse_url($url, PHP_URL_QUERY);
// parse_str can extract the variables into the global space or can put them into an array
// NOTE: for simplicity no validation is performed but in production you should perform validation
$params = array();
parse_str($queryString, $params);
// you can access the values like thid
echo $params['id']; // will output 2
echo $params['var']; // will output 'jj'
// I prefer this way, because it eliminates the posibility of overwriting another global variable
// with the same name as one of the parameters in the url.
// or you can tell parse_str to extract the variables into the global space
parse_str($queryString);
// or if you want to use the global scope
echo $id; // will output 2
echo $var; // will output 'jj'