Stack Class
From Habari Project
The Stack class allows a developer to create a "stack" of items for later output. This can be useful for creating a stack of scripts or CSS file references that should be added to the page output. Using the naming feature of the Stack class, a developer can ensure that only one script is added to the stack for a specific purpose.
Output a Stack
There are a few ways to generate output using the Stack class. Like many classes in Habari, Stack has ::get() and ::out() methods.
The ::get() method returns the values generated for a stack, and the ::out() method outputs the same values that would be returned by ::get().
To output a specific stack:
Stack::out('stack_name');
This causes all elements of the stack named stack_name to be output to the page in sequence. The values are not formatted.
To use a simple format of the values, this syntax is useful:
Stack::out('stack_name', ''); This outputs each element of the stack as if it was called as a parameter to PHP's sprintf() function. The string supplied as the second parameter to Stack::out() is the formatting string that is used to format each element. The most complex formatting technique allows callback functions as formatting functions: function myformatter($text){ return strrev($text) } Stack::out('stack_name', 'myformatter'); The second parameter to Stack:out() in this example is the name of a callback function. The function is called for each element of the stack, and the return value of that function is used for the stack output. In this case, the text of every element of the stack is reversed before it is output. Note that the callback function returns, and does not echo, regardless of whether the call to Stack is ::get() or ::out(). Also, the second parameter can call a class method by using the array('class_name', 'function_name') callback syntax, which may be useful for calling simple functions on the Format class.Alter a Stack
When you know the name of a stack, it is easy to queue values to it:
Stack::add('stack_name', $value);
$value is the value that you want to add to the stack. Calling ::add() this way will not ensure uniqueness.
To ensure that the element you are adding to the stack is unique for a purpose, use this:
Stack::add('stack_name', $value, 'element_name');
element_name is a name for the element that is added to the stack. Only one value can exist for each name in each stack. The second call to ::add() with the same element name replaces the existing stack element with a new value.
To remove an existing element from a stack:
Stack::remove('stack_name', 'element_name');
In this syntax, note that you are not able to remove values that have not been given names.
