using $variable inside preg_match function - php

I'm trying to learn MVC with PHP with some online courses. So in this tutorial, the teacher trying to detect a path.
$pathCheck=preg_match("#^{$link}$#",'$this->nowPath',$params);
print_r($params);
When he opens the project with desired path, let's say project/index.php, Array returns with 1.
If he try to write wrong path like project/asdasdas.php , Array returns with 0.
But for me, it returns empty.
Array ( ) Array ( ) Array ( ) Array ( ) Array ( )
I think the problem is preg_match part "#^{$link}$#"
I'm stucked.
I'm working on a localhost. AppServ (PHP Ver 7.3)
EDİT:
I'm adding my full codes to explain my situation a little bit better.
app.php
<?php
class App
{
protected $nowPath;
protected $nowMethod;
protected static $routes = [];
public function __construct()
{
$this->nowPath = $_SERVER['REQUEST_URI'];
$this->nowMethod = $_SERVER['REQUEST_METHOD'];
$this->startRoute();
}
public static function getAction($link, $path, $auth = false, $area = null)
{
self::$routes = ['GET', $link, $path, $auth, $area];
}
public function startRoute()
{
foreach (self::$routes as $routes) {
list($method, $link, $path, $auth, $area) = $routes;
$methodCheck = $this->nowMethod == $method;
$pathCheck=preg_match("#^{$link}$#",'$this->nowPath',$params);
print_r($params);
}
}
}
?>
route.php;
<?php
App::getAction('/index','/default/index',false); ?>

Fixed finally. I'm not fully understand but the teacher working with project/index folder.Mine was www/project/index. Maybe i made mistake on routing.

Related

PHP - What's the best way to handle empty function/method arguments?

I have the function/method below inside a class that I'm creating and I'm just wondering what's the best way to handle empty/null arguments.
For example, in the following example, if I wanted to just set just the category when calling the function, I would need to use:
$data = $class->get_top_headlines( null, 'technology' );
Is there any way of calling the function more efficiently? I know I could pass the arguments as an array instead, but just wondered if there's any way of doing something like:
$data = $class->get_top_headlines( $category='technology' ); and automatically leaving the other arguments as their default of null?
public function get_top_headlines( $query=null, $category=null, $country=null, $sources=null, $page_size=null, $page=null ){
$url = $this->api_url . $this->endpoint_top_headlines;
$params = array();
if ( $query !== null ){
$params['q'] = urlencode( $query );
}
if ( $category !== null ){
$params['category'] = $category;
}
if ( $country !== null ){
$params['country'] = $country;
}
if ( $sources !== null ){
$params['sources'] = $sources;
}
if ( $page_size !== null ){
$params['pageSize'] = $page_size;
}
if ( $page !== null ){
$params['page'] = $page;
}
$params['apiKey'] = $this->api_key;
$url_query = http_build_query( $params );
$url = $url . '?' . $url_query;
echo $url;
$obj = $this->get_response( $url );
return $obj;
}
Try passing an array, and then using an array_merge
$data = $class->get_top_headlines(['category' => 'technology']);
Then in your function, have an array of defaults, then do your merge.
$settings = array_merge($settings, $passedInArray);
http://php.net/manual/en/function.array-merge.php
I think
(null, 'technology' );
might be less actual coding but a different solution might be to use OOP. You said it's already a method of a class so you could do something like:
$obj = new thatClass;
$obj->technology = $technology;
$obj->get_top_headlines();
in the Class:
Class thatClass{
$technology = null;
$category = null;
$query = null;
//...
public function get_top_headlines(){
if ( $this->query !== null ){
$params['q'] = urlencode( $this->query );
}
if ( $this->category !== null ){
$params['category'] = $this->category;
}
if ( $this->technology !== null ){
$params['technology'] = $this->technology;
}
//method code..
}
//class code..
}
The problem with this approach is if you need to call that same function again passing a different parameter in the same class instance, depending on your application you might need to manually set back to null the previous parameter (now an object attribute)
I would solve this problem by creating a new class or data structure which will encapsulate all the logic of validating and generating the URL and then use it everywhere I need it.
Here's a sample class.
class HeadLineParameters
{
private $params = [];
public function setQuery($query)
{
// validate/transform query data
$this->params['q'] = urlencode($query);
return $this;
}
public function setCategory($category)
{
// validate/transform category data
$this->params['category'] = $category;
return $this;
}
public function generateUrl()
{
return http_build_query( $this->params );
}
}
$params = new HeadLineParameters;
$params->setQuery($query)
->setCategory($category);
You just pass one argument and you know that it's just an instance of HeadLineParameters.
$class->get_top_headlines($params);
This solution doesn't pollute your current class with unnecessary state or fields. It is easy to test, and it has only one job. You can extend it easily, you can set default values, you can also validate it as you like.
Edit: Why you shouldn't add more fields to your current class?
If you add more fields to your current class you'll be breaking the single responsibility principle, and any method of this class can change these fields too. It shouldn't be a problem if these fields really belong there and more methods require them. This is fine if you are using OOP.
I am not sure what other people think about passing associated arrays to functions, but they are hard to handle if you have no documentation available. I have had trouble with them when reading some external code, and most of time I wasn't sure what's the data I was dealing with.

Why getPostParameters doesn't work on symfony 1.4?

I have a form in symfony 1.4 which are created for each competence. My forms was created with success. But when I try to save my form I can't. I go to see my action code and the function getPostParameters seem dosn't work. I use getParameterHolder to see what's wrong in my parameters but after I put the good value the getPostParameters function doesn't work.
This is what I get from getParameterHolder:
sfParameterHolder Object
([parameters:protected] => Array
(
[professionnal_competence] => Array
(
[rayon_competence3] => 24
[rayon_competence9] => 22
[rayon_competence19] => 32
)
[module] => professionnal_subregion
[action] => saveCompetenceRadius
)
)
And my function:
public function executeSaveCompetenceRadius(sfWebRequest $request) {
$user = $this->getUser()->getGuardUser();
$q = ProfessionnalCompetenceQuery::create()
->addSelect('pc.*')
->where('pc.professionnal_id= ?', $user->getId());
$res = $q->execute();
$values = $request->getPostParameters(['professionnal_competence']);
$test = $request->getParameterHolder();
var_dump($values); print_r($values); print_r($request->getParameterHolder());
exit;
foreach ($res as $professionnalCompetence) {
foreach ($values['professionnal_competence'] as $k => $val) {
if ($k == 'rayon_competence' . $professionnalCompetence->getCompetenceId()) {
$professionnalCompetence->setRayonCompetence($val);
$professionnalCompetence->save();
}
}
}
return $this->renderComponent('professionnal_subregion', 'competenceRadius');
// return "test";
//return $this->renderPartial('professionnal_subregion/competenceradius');
}
This is my form:
class ProfessionnalCompetenceRadiusForm extends BaseProfessionnalCompetenceForm {
public function configure()
{
unset($this['rayon_competence']);
$this->widgetSchema['rayon_competence'.$this->object->getCompetenceId()] = new sfWidgetFormSelectUISlider(array('max'=>50,'step'=>1));
$this->widgetSchema->setHelp('rayon_competence'.$this->object->getCompetenceId(),'en kilomètres');
$this->widgetSchema->setLabel('rayon_competence'.$this->object->getCompetenceId(),'rayon');
$this->setValidator('rayon_competence'.$this->object->getCompetenceId(), new sfValidatorInteger(array('max'=>50)));
}
}
Someone has an idea or can help me ?? Because I try lot of thing but without success. Thank in advance :).
I think the error hides in this line:
$values = $request->getPostParameters(['professionnal_competence']);
You're passing an array to a function that takes a string. Try removing the brackets around 'professionnal_competence'.
EDIT: Scratch that. getPostParameters takes no parameters. getPostParameter, on the other hand, takes two - the first of which is the field name - a string. So, your code should be:
$values = $request->getPostParameter('professionnal_competence');
The error is here:
$values = $request->getPostParameters(['professionnal_competence']);
The function sfWebRequest::getPostParameters doesn't actually take parameters.
You can either access this array with [...], or use getPostParameter, which allows "safe" deep access:
$val = $request->getPostParameter('a[b]');
// basically the same as, but with error checks:
$val = $request->getPostParameters()['a']['b'];

Zend Cloud Infrastructure InstanceList - How to iterate through the list in the view?

I'm currently working on an Zend app which would control my Amazon EC2 instances through a simple web interface.
I was good until I arrived here:
$ec2 = $this->initEC2()->getEC2();
$instances = $ec2->listInstances();
$this->assign('instances', $instances);
Here's the code from my custom controller Action.php:
public function initEC2()
{
$key = MW_Config::AWS_ACCESS_KEY;
$secret = MW_Config::AWS_SECRET_KEY;
$region = 'us-east-1';
$infrastructure = Zend_Cloud_Infrastructure_Factory::getAdapter(array(
Zend_Cloud_Infrastructure_Factory::INFRASTRUCTURE_ADAPTER_KEY => 'Zend_Cloud_Infrastructure_Adapter_Ec2',
Zend_Cloud_Infrastructure_Adapter_Ec2::AWS_ACCESS_KEY => $key,
Zend_Cloud_Infrastructure_Adapter_Ec2::AWS_SECRET_KEY => $secret,
Zend_Cloud_Infrastructure_Adapter_Ec2::AWS_REGION => $region,
));
$this->ec2 = $infrastructure;
return $this;
}
public function getEC2()
{
if ($this->ec2 === null) {
$this->initEC2();
}
return $this->ec2;
}
I would like to know how I iterate correctly through the instance list to get a table in the view script???
I tried a while(), a for() and a foreach() but nothing was working... I browsed the code of Zend_Cloud_Insfrastructure_InstanceList (InstanceList.php) but I didn't find anything concluent...
From the documentation it appears that the class implements iterator interface PHP Iterator
You can do something like this:
foreach($it as $key => $value) {
var_dump($key, $value);
echo "\n";
}
Try to get 1 result first, using current:
var_dump($instances->current());

CakePHP get current URL without language prefix

I used this solution for i18n of my CakePHP 2.3 website.
When user in this URL: example.com/myController/myAction/param1/param2
I want to give link to example.com/eng/myController/myAction/param1/param2
This works well with this code inside my view file:
English
But when user in this URL: example.com/fre/myController/myAction/param1/param2
I can't link him to this URL: example.com/eng/myController/myAction/param1/param2
I can get the full URL with this:
fullURL = Router::url( $this->here, true );
$strippedURL = str_replace("http://example.com/fre/myController/myAction/param1/param2","myController/myAction/param1/param2",$fullURL)
But I need to make this for every language. Or I can strip first 22 characters from $fullURL. But they don't seem good solutions.
Do you have any suggestions?
Edit: Inside my Helper/View file I used this:
function getRelURL() {
$controller = $this->request->params['controller'];
$action = $this->request->params['action'];
$URL = "/".$controller."/".$action."/";
foreach ($this->request->params['pass'] as $p) {
$URL .= urlencode($p)."/";
}
}
I would be happy if you can recommend better alternative.
I used a slightly different approach that seems to work well, even though I have not tested it with named parameters and all other routing features.
I created the following function in AppHelper:
public function urlLanguage($lang) {
static $hereUrl=null;
if (empty($hereUrl)) {
$hereUrl = $this->request->params;
unset ( $hereUrl ['models'] );
unset ( $hereUrl ['named'] );
unset ( $hereUrl ['paging'] );
if (isset ( $hereUrl ['pass'] )) {
foreach ( $hereUrl ['pass'] as $pass ) {
$hereUrl [] = $pass;
}
unset ( $hereUrl ['pass'] );
}
}
return array_merge( $hereUrl, array ('language' => $lang ) );
}
and use it in the View as follows:
foreach ($languages as $lang=>$langDesc) {
echo $this->Html->link($languageDesc, $this->Html->urlLanguage($lang));
}
where $languages is an array with all the available language. I skipped the HTML around it the link itself.
I followed the instructions here for setting up the routes and language switching.

How to determine user defined function parameters names before calling it?

In PHP, I have created a user defined function. Example:
<?php
function test($one, $two) {
// do things
}
?>
I would like to find the names of the function parameters. How would I go about doing this?
This is an example of what I would like:
<?php
function test($one, $two) {
// do things
}
$params = magic_parameter_finding_function('test');
print_r($params);
?>
This would output:
Array
(
[0] => one
[1] => two
)
Also this is very important that I am able to get the user defined function parameter names outside the scope of the function. Thanks in advance!
You can do this using reflection...
$reflector = new ReflectionFunction('test');
$params = array();
foreach ($reflector->getParameters() as $param) {
$params[] = $param->name;
}
print_r($params);
you can use count_parameter a php built in function

Categories