Tag Archives: Curly bracket programming languages

Zend_View_Helper_InlineScript Appends Scripts Twice

Double Trouble

duplicate
This is a well known problem, which is well described as a bug in Zend Framework’s issue tracker. Once you add some scripts with the inlineScript helper you’ll receive them twice in the code. This makes the page slower and leads to some crashes.

$scripts->appendFile('my-file1.js')
        ->appendFile('my-file2.js')
        ->appendScript('alert("test")');

This will print the alert twice.

<script src="my-file1.js"></script>
<script src="my-file2.js"></script>
<script>
//<!--
alert("test");
//-->
</script>
<script>
//<!--
alert("test");
//-->
</script>

Quick Solution

Although this is the worst solution I’ve ever made – it works! There is a check for duplicates in the HeadScript helper around line 240:

if (!$this->_isDuplicate($content)) {
...

and then a check in the _isDuplicate method(), ~ line 270:

if (($item->source === null)
    && array_key_exists('src', $item->attributes)
    && ($file == $item->attributes['src']))
{
    return true;
}

The thing you’ve to do is to add such a check for the appendScript() and not only for appendFile() method – again ~ line 230:

case 'script':
	if (!$this->_isDuplicate($content)) {
	    $item = $this->createData($type, $attrs, $content);
	    if ('offsetSet' == $action) {
	        $this->offsetSet($index, $item);
	    } else {
	        $this->$action($item);
	    }
	}
	break;

And then slightly modify the _isDuplicate method:

foreach ($this->getContainer() as $item) {
    if (($item->source === null)
        && array_key_exists('src', $item->attributes)
        && ($file == $item->attributes['src']))
    {
        return true;
    }
    if ($item->source == $file) {
        return true;
    }
}
return false;

Zend Framework: Inject JavaScript Code in a Action/View

There is a view helper that can inject a head or inline script into your code.

Simply by putting some JavaScript code into the view script wont do the job, because the .phtml file is grabbed and parsed by the Zend Framework and thus the code there wont be parsed as JavaScript and it wont be executed as well by the browser.

The Most Simple Way …

is to put some place holder into the layout .phtml file and than from the controller’s action you can assign some JS code:

// layout.phtml
<?php
...
echo $this->layout()->scriptTags;
...
<?php
 
class IndexController extends Zend_Controller_Action
{
	public function indexAction() 
	{
		$this->view->layout()->scriptTags = '<script src="my.js"></script>';	
	}	
}

Solution No. 2

Although the first solution is correct it’s not the most clearest way, because you put the JavaScript code into the PHP, and this sooner or later becomes a mess.

<?php
 
class IndexController extends Zend_Controller_Action
{
	public function indexAction() 
	{
		$this->view->layout()->scriptTags = '<script src="my.js"></script>';
						  . '<script>alert("here\'s my" + "test")</script>';
	}	
}

The IDE is not highlighting the code, and you’ve to deal with too many quotes, which is bad! There is a better solution however – the inline script:

// script tags
/* @var $scripts Zend_View_Helper_InlineScript */
$scripts = $this->view->inlineScript();
$scripts->appendFile('my.js');

Simply the Best

Yeah, the best solution is something even better than the second one. Although the solution I’ve just mentioned is fine for including JS files, when you’ve to add some JS code you’ll have to put it again into the PHP.

$msg = 'some dynamically generated message';
 
// script tags
/* @var $scripts Zend_View_Helper_InlineScript */
$scripts = $this->view->inlineScript();
$scripts->appendFile('my.js');
$scripts->appendScript('alert("' . $msg . '")');

If there’s no relation between JavaScript and PHP you can simply put all this code into a separate .js file and load it from there. This is by the way the best solution because the file is cached by the browser, if the cache is enabled. But most of the time you perhaps have to send some variables from PHP to the JavaScript code.

It would be perfect if you had some kind of a variable placeholders – exactly as you have it in the Zend Framework’s view scripts!

Another View

This is completely possible – just forget about the default view – it renders the view script and it’s bind to the /views/scripts folder. You can make another, completely new, view instead! Here’s some source:

$view = new Zend_View();
$view->setBasePath('path_to_the_js_folder');
 
$view->msg = 'Some dynamically generated message';
 
// script tags
/* @var $scripts Zend_View_Helper_InlineScript */
$scripts = $this->view->inlineScript();
$scripts->appendFile('my.js');
$scripts->appendScript($view->render('inline.js'));

Thus now in the JS file you can have some placeholders!

// inline.js
 
// some js code
// ...
alert('<?php echo $this->msg ?>');

Friday Algorithms: Quicksort – Difference Between PHP and JavaScript

Here’s some Friday fun. Let me show you one sorting algorithm, perhaps the most known of all them – the quick sort, implemented both on PHP and JavaScript. Although the code look similar between both languages, there are few differences, that show the importance of the syntax knowledge!

1. PHP

<?php
 
    $unsorted = array(2,4,5,63,4,5,63,2,4,43);
 
    function quicksort($array)
    {
        if (count($array) == 0)
            return array();
 
        $pivot = $array[0];
        $left = $right = array();
 
        for ($i = 1; $i < count($array); $i++) {
            if ($array[$i] < $pivot)
                $left[] = $array[$i];
            else
                $right[] = $array[$i];
        }
 
        return array_merge(quicksort($left), array($pivot), quicksort($right));
    }
 
    $sorted = quicksort($unsorted);
 
    print_r($sorted);

2. JavaScript

var a = [2,4,5,63,4,5,63,2,4,43];
 
function quicksort(arr)
{
    if (arr.length == 0)
        return [];
 
    var left = new Array();
    var right = new Array();
    var pivot = arr[0];
 
    for (var i = 1; i < arr.length; i++) {
        if (arr[i] < pivot) {
           left.push(arr[i]);
        } else {
           right.push(arr[i]);
        }
    }
 
    return quicksort(left).concat(pivot, quicksort(right));
}
 
console.log(quicksort(a));

Note that the first conditional statement is quite important! While in PHP the count function will return 0 either on a NULL value or an empty array and you can substitute it with something like count($array) < 2

if (count($array) < 2)
	return $array;

in JavaScript you cannot use that because of the presence of the ‘undefined’ value when an “empty” array is passed as an argument. Thus you’ve the conditional above:

// this will result with an error
if (arr.length < 2)
        return arr;

Coming Up Next …

An iterative version of the algorithm next Friday!

JSON and Zend Framework? – Zend_Json

That’s really a good Zend Framework’s class that help you do the encode/decode job very easily. First of all it escapes everything for you and second it prints a correct/valid code. Note that sometimes if you have a trailing whitespace after the closing PHP tag – ?> that will result in an error.

Here’s some code:

public function jsonAction()
{
	$data = array(3,4,'test', 'my-name' => 3,4);
 
	echo Zend_Json::encode($data);
 
	$this->_helper->viewRenderer->setNoRender(true);
	$this->view->layout()->disableLayout();
}

and the result is:

{"0":3,"1":4,"2":"test","my-name":3,"3":4}

Note that all integers are printed without double quotes – which saves some space!

JavaScript Objects Coding Style

JavaScript vs. PHP

Continuing from my post about PHP arrays coding style and following the comments of that post, I’d like to write a bit about JavaScript objects’ coding style.

You perhaps know that the term object is quite undefined or under estimated in the JavaScript world, but I’d speak about the key/value pairs in JS commonly formatted like that:

var obj = { key : 'value' }

Here you can add more and more key/value pairs, but what’s different from the PHP associative arrays and what’s the same and should be cosidered.

The Same as PHP?

I wrote about the alignment in PHP and hashes. Than I showed how I align them:

$arr = array(
   'short'   => 'val',
   'longkey' => 'val'
);

In JavaScript you should use the same technique of alignment:

var obj = {
   'short'   : 'val',
   'longkey' : 'val'
};

Some Differences

Yes, there are more differences, which is normal. First of all you don’t have the => notation in JavaScript and a : is used. Second and most important you cannot add a trailing comma after the last key/value pair. Note that in PHP that’s fine!

// that will throw an error in MSIE
var obj = {
   'short'   : 'val',
   'longkey' : 'val',
};

while this is OK in PHP and it’s encouraged:

$arr = array(
   'short'   => 'val',
   'longkey' => 'val',
);