views:

171

answers:

4

Is it bad practice to concatenate objects when used in this context:

$this->template->head .= new View('custom_javascript')

This is the way i normally add extra css/js stuff to specific pages. I use an MVC structure where my basic html template has a $head variable which I set in my main Website_controller. I have used this approach for a while as it means I can just add bits and pieces of css/js stuff from whichever page/controller needs it. But having come across a problem in PHP 5.1.6 where the above code results in "Object ID #24", the result of toString() not being called i think, I am rethinking whether i should just fix this to work in PHP 5.1.6 or if i should rethink this approach in general.

Any pointers appreciated!

+1  A: 

You can always use View as a factory object, passing it as string to template with a render() function ( or whatever you'd like to call it ), so the code you have there would look something like;

$this->template->head .= View::factory('custom_javascript')->render()

being rendered the moment before it's passed to template.

Kohana 3 for example uses this pattern to work with views / templates, you can read more about it at unofficial wiki

Kemo
Thanks Kemo, I'm on Kohana 2.3.4 but the example you've provided will work in that version too. Do you think it's ok practice to use this type of approach in the context of adding controller specific js/css?
franko75
A: 

Seems like wrong approach to me. It's bad idea to construct templates somewhere in controller (judging by your code) by concatenating strings. Better insert all needed blocks directly from teamplate like this:

controller:

// setup template variable
$this->template->var_script = 'custom_javascript';
$this->template->render();

template:

<html>
<head>
<title><?= $title ?></title>
<?= Html::script($var_script) ?>
Sergei
+1  A: 

WTF? You can only concatenate strings - so (assuming it doesn't just throw an error and die) this code will serialize the object before appending it to a string. While you may have a toString() method to generate the HTML, this is not going to work with the 'new' construct - which is not a function.

Presumably you want to generate some html code from the object at some point. In which case you should be something like:

$obj=new View('custom_javascript')
$this->template->head . $obj->generateHtml();

Although creating a whole new object just to wrap a string in some html markup is very wasteful - I'd go with a set of methods for doing this - say...

$this->template->head->addJs('custom_javascript');
$this->template->head->addCSS('make_it_look_funky');
...

C.

symcbean
A: 

Objects with a magic __toString() method are only converted automatically to strings when they're used as strings starting from PHP 5.2.0. In this case, since you use 5.1.6, you must cast the object as a string by hand, so that would be:

$this->template->head .= (string) new View('custom_javascript');
Seldaek