Can an Abstract Class in PHP Have a Default Method? - php

I've most certainly got something very basic wrong here.
Here is the code that is part of my Abstract Class:
private $outarray = null;
public function add_to_array($ahref, $docname, $description) {
$row = array('ahref' => $ahref, 'docname' => $docname, 'description' => $description);
if (!isset($this->outarray)) {
$this->outarray = array();
}
array_push($this->outArray, $row);
}
When I step through the code, though, the outArray remains null. It is never created and never populated.
I'm still green with PHP, but this help doc seems to leave me believing that this is OK to do:
http://www.php.net/manual/en/language.oop5.abstract.php
...particularly where they are declaring the Common method printOut() that performs some action.
I've got 5 elements I am trying to populate outArray with, but each of the 5 times I circle into this function, I come out with outArray being NULL.

Variables are case sensitive. You have in one place $this->outarray and in array_push you have $this->outArray

Ugh.
PHP is case sensitive, but it does not complain about it because it was assuming I had another variable declared on the fly.
Correct way:
public function add_to_array($ahref, $docname, $description) {
$row = array('ahref' => $ahref, 'docname' => $docname, 'description' => $description);
if (!isset($this->outarray)) {
$this->outarray = array();
}
array_push($this->outarray, $row);
}

Related

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'];

pass value for last default parameter of function

From very long time i am working on php.
But one question may I have no idea about
like I have one function as bellow:
function hello($param1, $param2="2", $param3="3", $param4="4")
Now whenever I will use this function and if I need 4th params thats the $param4 then still I need to call all as blank like this one:
hello(1, '', '', "param4");
So is there any another way to just pass 1st and 4th param in call rather then long list of blanks ?
Or is there any other standard way for this ?
There was an RFC for this named skipparams but it was declined.
PHP has no syntactic sugar such as hello(1, , , "param4"); nor hello(1, default, default, "param4"); (per the RFC) for skipping optional parameters when calling a function.
If this is your own function then you can choose the common jQuery style of passing options into plug-ins like this:
function hello( $param1, $more_params = [] )
{
static $default_params = [
'param2' => '2',
'param3' => '3',
'param4' => '4'
];
$more_params = array_merge( $default_params, $more_params );
}
Now you can:
hello( 1, [ 'param4'=>'not 4, muahaha!' ] );
If your function requires some advanced stuff such as type hinting then instead of array_merge() you will need to manually loop $more_params and enforce the types.
One potential way you can do this, while a little bit hacky, may work well in some situations.
Instead of passing multiple variables, pass a single array variable, and inside the function check if the specific keys exist.
function hello($param1, $variables = ["param2" => "2", "param3" => "3", "param4" => "4"]) {
if(!array_key_exists("param2", $variables)) $variables['param2'] = "2";
if(!array_key_exists("param3", $variables)) $variables['param3'] = "3";
if(!array_key_exists("param4", $variables)) $variables['param4'] = "4";
echo "<pre>".print_r($variables, true)."</pre>";
}
This will allow you to set "param4" in the above variable, while still remaining default on all of the others.
Calling the function this way:
hello("test", ["param4" => "filling in variable 4"]);
Will result in the output being:
Array
(
[param4] => filling in variable 4
[param2] => 2
[param3] => 3
)
I don't generally recommend this if it can be avoided, but if you absolutely need this functionality, this may work for you.
The key here is that you have a specifically named index inside the array being passed, that you can check against inside the function itself.
The answer, as I see it, is yes and no.
No, because there's no way to do this in a standard fashion.
Yes, because you can hack around it. This is hacky, but it works ;)
Example:
function some_call($parm1, $parm2='', $parm3='', $parm4='') { ... }
and the sauce:
function some_call_4($parm1, $parm4) {
return some_call($parm1, '', '', $parm4);
}
So if you make that call ALOT and are tired of typing it out, you can just hack around it.
Sorry, that's all I've got for you.
It is an overhead, but you can use ReflectionFunction to create a class, instance of which that can be invoked with named parameters:
final class FunctionWithNamedParams
{
private $func;
public function __construct($func)
{
$this->func = $func;
}
public function __invoke($params = [])
{
return ($this->func)(...$this->resolveParams($params));
}
private function resolveParams($params)
{
$rf = new ReflectionFunction($this->func);
return array_reduce(
$rf->getParameters(),
function ($carry, $param) use ($params) {
if (isset($params[$param->getName()])) {
$carry[] = $params[$param->getName()];
} else if ($param->isDefaultValueAvailable()) {
$carry[] = $param->getDefaultValue();
} else {
throw new BadFunctionCallException;
}
return $carry;
},
[]
);
}
}
Then you can use it like this:
function hello($param1, $param2 = "2", $param3 = "3", $param4 = "4")
{
var_dump($param1, $param2, $param3, $param4);
}
$func = new FunctionWithNamedParams('hello');
$func(['param1' => '1', 'param4' => 'foo']);
Here is the demo.

How does $this->print = $render work in Drupal?

I understand that this is object oriented, and that you are essentially passing the value of the [print] cell from the [this] array into a separate variable called $render.
But, does this automatically cause the information to be displayed on screen?
see code for reference:
public function setPrintRender(array $render) {
$this->print = $render;
}
Or is this information going to respectfully stay quietly in that variable until some other process grabs it and then displays it on the screen?
UPDATE
So, maybe this part of the code is what actually prints the info?
public function build() {
$output = array();
foreach ($this->panes as $pane) {
$output[$pane->getId()] = $this->buildPane($pane);
}
if ($render = $this->pos->getState()->getPrintRender()) {
$output[] = array(
'#prefix' => '<div class="element-invisible"><div class="pos-print">',
'#suffix' => '</div></div>',
'print' => $render,
);
}
return $output;
}
No, it doesn't cause it to be rendered.
A variable $render is being passed into setPrintRender() which then sets it to an internal variable called $this->print.
This is known as a setter. You will generally have a getter and setter method for every publicly available variable.

How specific should your functions be in Zend_Model?

if someone could help me with a conceptual question it would be great: Suppose I have a model that deals with a table called Persons. Normally I would have a standard fetch function like this:
public function fetchPersonById($person_id)
{
$result = 0;
if ((int)$person_id > 0) {
$select = $this->select()
->from($this->_name, array('Id' => 'Person_Id',
'Name' => 'Person_Name',
'Age' => 'Person_Age',
'Sex' => 'Person_Sex'));
->where('Person_Id = ?', $person_id);
$result = $this->fetchRow($select);
}
return $result;
}
Now suppose for some reason I need to fetch a person's Sex by it's Name.. and later on it's age by it's name. Would you them add different functions like:
public function fetchPersonSexByName($person_name)
{
// ...
->from($this->_name, array('Sex' => 'Person_Sex');
->where('Person_Name = ?', $person_name); ...
// ...
}
and so on... After a while you could see yourself with thousands of short methods like this.. Are you guys that specific or you wether pull the whole record (fetchall) and than later in the code just keep the column you want to use? On this case wouldn't you be breaking the whole MVC because if I want to get
someone's Sex my model (or whoeve is calling the function) would need to know the columns name in the database?
I also tought about doing something more generic like
public function $this->fetchColumnA_By_ColumnB_ColumnBValue($columnA_name,
$columnB_name, $columnA_name)
{
//...
}
And than have my short methods to be calling this more flexible column. So that I would have something like:
public function fetchPersonSexByName($person_name)
{
//...
$this->fetchColumnA_By_ColumnB_ColumnBValue('sex', 'name', 'martin');
}
Anyway.. How do you guys approach this probably common issue?
I would tend to do a version of your last generic example. The generic method would be protected (or even private) and your more specific (public) methods would call this. To avoid code repetition.
However, I'm not sure how generic I would go. May be just...
protected function _fetchColumnById($id, $column) {...}
protected function _fetchColumnByName($name, $column) {...}
...but this would depend on the requirements.
you could see yourself with thousands of short methods
If you think you'll get to 1000's of requests, then it might be better to read the whole record(s) and cache this somehow?
What you could do is make a magic __call function in your model or in his parent.
If some method doesn't exist it will go thru that magic function. Something like:
class Model_Test {
public function __call($method, $args) {
if(preg_match('/fetch([a-zA-Z]+)by([a-zA-Z]+)/i', $method, $result)) {
$fetch = $result[1];
$column = $result[2];
echo 'SELECT ' . $fetch . ' FROM test WHERE ' . $column . ' = "' . (string)$args[0] . '"';
//build your query here and make sure you make it secure with bind param, etc.
} else {
//call parent __call? Or throw an error?
}
}
}
$model = new Model_test();
$model->fetchSexByName('martin');
Just a quick example, offcourse you need to work it out. Success!

PHP: Class property chaining in variable variables

So, I have a object with structure similar to below, all of which are returned to me as stdClass objects
$person->contact->phone;
$person->contact->email;
$person->contact->address->line_1;
$person->contact->address->line_2;
$person->dob->day;
$person->dob->month;
$person->dob->year;
$album->name;
$album->image->height;
$album->image->width;
$album->artist->name;
$album->artist->id;
etc... (note these examples are not linked together).
Is it possible to use variable variables to call contact->phone as a direct property of $person?
For example:
$property = 'contact->phone';
echo $person->$property;
This will not work as is and throws a E_NOTICE so I am trying to work out an alternative method to achieve this.
Any ideas?
In response to answers relating to proxy methods:
And I would except this object is from a library and am using it to populate a new object with an array map as follows:
array(
'contactPhone' => 'contact->phone',
'contactEmail' => 'contact->email'
);
and then foreaching through the map to populate the new object. I guess I could envole the mapper instead...
If i was you I would create a simple method ->property(); that returns $this->contact->phone
Is it possible to use variable variables to call contact->phone as a direct property of $person?
It's not possible to use expressions as variable variable names.
But you can always cheat:
class xyz {
function __get($name) {
if (strpos($name, "->")) {
foreach (explode("->", $name) as $name) {
$var = isset($var) ? $var->$name : $this->$name;
}
return $var;
}
else return $this->$name;
}
}
try this code
$property = $contact->phone;
echo $person->$property;
I think this is a bad thing to to as it leads to unreadable code is is plain wrong on other levels too, but in general if you need to include variables in the object syntax you should wrap it in braces so that it gets parsed first.
For example:
$property = 'contact->phone';
echo $person->{$property};
The same applies if you need to access an object that has disalowed characters in the name which can happen with SimpleXML objects regularly.
$xml->{a-disallowed-field}
If it is legal it does not mean it is also moral. And this is the main issue with PHP, yes, you can do almost whatever you can think of, but that does not make it right. Take a look at the law of demeter:
Law of Demeter
try this if you really really want to:
json_decode(json_encode($person),true);
you will be able to parse it as an array not an object but it does your job for the getting not for the setting.
EDIT:
class Adapter {
public static function adapt($data,$type) {
$vars = get_class_vars($type);
if(class_exists($type)) {
$adaptedData = new $type();
} else {
print_R($data);
throw new Exception("Class ".$type." does not exist for data ".$data);
}
$vars = array_keys($vars);
foreach($vars as $v) {
if($v) {
if(is_object($data->$v)) {
// I store the $type inside the object
$adaptedData->$v = Adapter::adapt($data->$v,$data->$v->type);
} else {
$adaptedData->$v = $data->$v;
}
}
}
return $adaptedData;
}
}
OOP is much about shielding the object's internals from the outside world. What you try to do here is provide a way to publicize the innards of the phone through the person interface. That's not nice.
If you want a convenient way to get "all" the properties, you may want to write an explicit set of convenience functions for that, maybe wrapped in another class if you like. That way you can evolve the supported utilities without having to touch (and possibly break) the core data structures:
class conv {
static function phone( $person ) {
return $person->contact->phone;
}
}
// imagine getting a Person from db
$person = getpersonfromDB();
print conv::phone( $p );
If ever you need a more specialized function, you add it to the utilities. This is imho the nices solution: separate the convenience from the core to decrease complexity, and increase maintainability/understandability.
Another way is to 'extend' the Person class with conveniences, built around the core class' innards:
class ConvPerson extends Person {
function __construct( $person ) {
Person::__construct( $person->contact, $person->name, ... );
}
function phone() { return $this->contact->phone; }
}
// imagine getting a Person from db
$person = getpersonfromDB();
$p=new ConvPerson( $person );
print $p->phone();
You could use type casting to change the object to an array.
$person = (array) $person;
echo $person['contact']['phone'];
In most cases where you have nested internal objects, it might be a good time to re-evaluate your data structures.
In the example above, person has contact and dob. The contact also contains address. Trying to access the data from the uppermost level is not uncommon when writing complex database applications. However, you might find your the best solution to this is to consolidate data up into the person class instead of trying to essentially "mine" into the internal objects.
As much as I hate saying it, you could do an eval :
foreach ($properties as $property) {
echo eval("return \$person->$property;");
}
Besides making function getPhone(){return $this->contact->phone;} you could make a magic method that would look through internal objects for requested field. Do remember that magic methods are somewhat slow though.
class Person {
private $fields = array();
//...
public function __get($name) {
if (empty($this->fields)) {
$this->fields = get_class_vars(__CLASS__);
}
//Cycle through properties and see if one of them contains requested field:
foreach ($this->fields as $propName => $default) {
if (is_object($this->$propName) && isset($this->$propName->$name)) {
return $this->$propName->$name;
}
}
return NULL;
//Or any other error handling
}
}
I have decided to scrap this whole approach and go with a more long-winded but cleaner and most probably more efficient. I wasn't too keen on this idea in the first place, and the majority has spoken on here to make my mind up for me. Thank for you for your answers.
Edit:
If you are interested:
public function __construct($data)
{
$this->_raw = $data;
}
public function getContactPhone()
{
return $this->contact->phone;
}
public function __get($name)
{
if (isset($this->$name)) {
return $this->$name;
}
if (isset($this->_raw->$name)) {
return $this->_raw->$name;
}
return null;
}
In case you use your object in a struct-like way, you can model a 'path' to the requested node explicitly. You can then 'decorate' your objects with the same retrieval code.
An example of 'retrieval only' decoration code:
function retrieve( $obj, $path ) {
$element=$obj;
foreach( $path as $step ) {
$element=$element[$step];
}
return $element;
}
function decorate( $decos, &$object ) {
foreach( $decos as $name=>$path ) {
$object[$name]=retrieve($object,$path);
}
}
$o=array(
"id"=>array("name"=>"Ben","surname"=>"Taylor"),
"contact"=>array( "phone"=>"0101010" )
);
$decorations=array(
"phone"=>array("contact","phone"),
"name"=>array("id","name")
);
// this is where the action is
decorate( $decorations, &$o);
print $o->name;
print $o->phone;
(find it on codepad)
If you know the two function's names, could you do this? (not tested)
$a = [
'contactPhone' => 'contact->phone',
'contactEmail' => 'contact->email'
];
foreach ($a as $name => $chain) {
$std = new stdClass();
list($f1, $f2) = explode('->', $chain);
echo $std->{$f1}()->{$f2}(); // This works
}
If it's not always two functions, you could hack it more to make it work. Point is, you can call chained functions using variable variables, as long as you use the bracket format.
Simplest and cleanest way I know of.
function getValueByPath($obj,$path) {
return eval('return $obj->'.$path.';');
}
Usage
echo getValueByPath($person,'contact->email');
// Returns the value of that object path

Categories