I'm trying to get the controller, method and queries from a URL array. Something like this:
'home/news/[day]/[month]/[slug]/'
I need some regex which will give me the following:
Controller: home
Method: News
Arguments: day, month, slug
For the arguments, it'd be nice if I could somehow get the name inside the brackets so I can put them into an associative array in PHP. e.g: ("day"=>$day).
I'm really stuck with this, and tried looking at several PHP frameworks for guidance but nothing really accomplishes exactly what I want above, especially using regex.
preg_match('{/home/news/(?<day>\d{1,2})/(?<month>\d{1,2})/(?<slug>[\w-]+)}',
'/home/news/10/02/foo',
$matches);
$matches is now
array (
0 => '/home/news/10/02/foo',
'day' => '10',
1 => '10',
'month' => '02',
2 => '02',
'slug' => 'foo',
3 => 'foo',
)
If you're always going to have /:controller/:method/:args you might as well use explode:
$args = explode('/', $url);
$controllerName = array_shift($args);
$method = array_shift($args);
$controller = new $controllerName;
$response = $controller->$method($args);
Related
Is there a more compact way to send an array to a function?
Here's what I'm currently doing:
$data = array(
'id' => '1'
);
$result = $this->Tests_model->DoSomething($data);
What I'd like to do is just:
$result = $this->Tests_model->DoSomething(array('id' => '1'));
or
$result = $this->Tests_model->DoSomething(('id' => '1'));
...but I can't seem to format the data inside the ( and ). I still want to pass an array, for better code-reuse. Is there a way to do this?
This line
$result = $this->Tests_model->DoSomething(array('id' => '1'));
is completely valid and can be used.
You need to change the third example to make it work. What you're looking for is
$result = $this->Tests_model->DoSomething(['id' => '1']);
The syntax ['id' => '1'] is just another way of writing array('id' => '1') they produce the exact some thing.
One last way to create an array and add a key/value pair to it is like this.
$data['id'] = '1'; //assigns a value of '1' to the key 'id' in an array named $data.
The above is just alternate syntax for writing.
$data = array('id' => '1');
None of these variations on syntax is better or worse other than in terms of "readability" which is often a matter of opinion.
Everything you could want to know about arrays in the PHP Documentation.
I want to call the function from an array .My code is
$params = array(
'df' => $this->_data['df'],
'fl' => implode(',', $this->_data['fl']),
'wt' => $this->_data['wt'],
'q' => $this->_data['select'],
'sort' => '',
'fq' => implode(' ', $fq),
'indent' => 'true',
'start' => $this->_data['range'][0],
'rows' => $this->_data['range'][1],
'defType' => $this->_data['defType'],
'qf' => implode(' ', $qf),
);
i want to call function-"WordSplit" from an array:
'q' => WordSplit($this->_data['select']);
Is it possible to do this in PHP?
Thanks in Advance!!!
As has been said, "the answer is, 'yes.'" WordSplit() is a function, therefore a call to that function is a valid expression. It can be used to provide a value for an array-element.
Now, what I would do, instead, is to add a new statement after the existing one:
$params['q'] = WordSplit(params['q']);
Why? Because the very-harried person who's reading our code, someday in the future, might not notice that element 'q' is being handled differently! Purely for the sake of readability (and possible future maintainability), I would choose to do this as a separate statement. The $params array is first "assembled," in a construct where the action for every element in the array is more-or-less the same. Then, element 'q' is manipulated. (And I would place all other such "manipulations" adjacent to this one. "Clarity... Clarity...")
ok.. I know I can find help here :)
I am barely out of noobhood so be gentle :)
I'm trying to fetch data from a db and use it to call a pie chart in GoogChart so here is my problem... some code like db connections etc. is skipped to get to the point.
First we look at the array GoogChart uses to pass the info:
$data = array(
'8' => 6,
'3' => 3,
'9' => 2,
);
Now we look at how I am trying to do it pulling the data from a db:
//connect and query here
while ($row=mysql_fetch_array($query)){
$viewid=trim($row['id']);
$total_views=trim($row['views']);
// trimmed cuz I can't sort it out
$dat = "'$viewid' => $total_views,"; //problem likely here
}
$data = array(
$dat
);
When I echo the $dat, I get this:
'8' => 6,'3' => 3,'9' => 2,
So theoretically, it should work??? But noop :(
There may be a totally different way of doing this but I'm stumped... didn't take much to do it either lol.
What you're doing is creating an array with one element: "'8' => 6,'3' => 3,'9' => 2,".
Instead, you should be populating an array as you go:
$data = array(); // create the array
while ($row=mysql_fetch_array($query)){
$viewid=trim($row['id']);
$total_views=trim($row['views']);
// use the $viewid as the key and $total_views as the value
$data[ $viewid ] = $total_views;
}
Of course, you could also do (not certain if this could help you, but it is an option):
$data = array(); // create the array
while ($row=mysql_fetch_array($query)){
// use the $viewid as the key and $total_views as the value
$data[ trim($row['id']) ] = trim($row['views']);
}
I'm not familiar with CakePHP too close. Recently I've ran into problem using Model. I need to get exaclty one row from database, modify some columns values and save it back. Pretty simple, right?
What do I try to do:
$condition = array('some_id_column' => $another_models_id);
$model = $this->MyModel->findFirst($condition);
BUT i get FALSE in $model variable. At hte same time
$condition = array('some_id_column' => $another_models_id);
$model = $this->MyModel->findAll($condition);
returns array. Its structure is something like:
array (
0 =>
array (
'MyModel' =>
array (
'id' => '1',
'some_id_column' => '123456',
'some_field' => 'some text',
...
),
),
I'd go with findAll if it did not return an array of arrays, but array of models (in my case - of one model). What do I want to achieve:
$condition = array('some_id_column' => $another_models_id);
$model = $this->MyModel->findFirst($condition);
$model->some_field = 'some another text';
$model->save();
Could you help me out to understand how it's usually done in CakePHP?
I'd also like to hear why findAll finds row and findFirst fails to find it... It just does not make sense to me... They should work in almost the same way and use the same database APIs...
If I can not do what I want in CakePHP, would you write a receipt how it is usually done there ?
There is no such method as findFirst.
You're probably looking for find('first', array('conditions' => array(...))).
I recently faced a design problem with PHP. I noticed that in a function you can pass as parameter an array. I didn't noticed the powerful of this thing first, but now i'm obsessed with arrays.
For example, in my template class i have to pass some variables and some mysqli_results into the template file (like phpbb do). And i was wondering which one of the following possibilities is the best.
# 1
$tpl = new template(array(
'vars' = array('var1' => 'val1', 'var2' => 'val2'),
'loops' = array('loop1' => $result1, 'loop2' => $result2)
));
# 2
$tpl = new template;
$tpl->assignVars(array(
'var1' => 'val1',
'var2' => 'val2'
));
$tpl->assignloops(array(
'loop1' => $result1,
'loop2' => $result2
));
# 3
$tpl = new template;
$tpl->assignVar('var1', 'val1');
$tpl->assignVar('var1', 'val1');
$tpl->assignLoop('loop1', $result1);
$tpl->assignLoop('loop2', $result2);
Or if there is something better. I was even thinking about creating a db class that performs a query as follow:
$result = $db->fastQuery(array(
'select' => 'user-name',
'from' => $table,
'where' => array('user-id' => 123, 'user-image' => 'none'),
'fetch' => true
));
Oh my God, i'm really obsessed.
If it was up to me I would chose #1, I don't like nesting objects and arrays only if it is necessary. by doing so I keep my code simple.
and if you follow your obsession you may end up writing a full ORM.
#4
Allowing both:
function assign($name, $val = null)
{
if (is_array($name)) {
// loop through and assign
} else {
// assign single var
}
}
This is akin to overloading techniques you would see in C++/Java.
You can also allow #1 by just calling assign in the constructor. It is not uncommon in OOP programming to have the constructor allow a shortcut to setting properties that can also be set in other methods.