I am using an array of objects to store data to render a page.
A few examples of the type of data each object can contain:
- PHP filepath for an include
- CSS filepath for CSS files
- Meta data of the page
- Element data to build page elements
- Etc...
I have an HTML template file that I parse with PHP and replace certain tags in the template with data stored in the objects. A template tag looks like:
<!-- @CMS;TYPE=TITLE !-->
<!-- @CMS;TYPE=CSS !-->
These tags can also have more attributes:
<!-- @CMS;TYPE=JS-FILES;POS=TOP !-->
<!-- @CMS;TYPE=JS-FILES;POS=BOTTOM !-->
The tags above contain a position and thus you can place your content of the same type in the top or the bottom of the template.
The data objects all use the same abstract class and have the same render function:
class PhpFragment extends FragmentBase {
public function render() {
//... render output for this type of data
}
}
class CssFragment extends FragmentBase {
public function render() {
//... render output for this type of data
}
}
class MetaFragment extends FragmentBase {
public function render() {
//... render output for this type of data
}
}
This way I can use an universal function to render all the objects, unregarding the type of data it contains.
The Challenge
I need a way to quickly find certain objects inside the array. When I reach a certain tag inside the template, I need to render the data of the objects that match the type (and position if applicable) of this tag.
In my previous design I used an object with a lot of class properties that hold instances of FragmentBase
, like:
class pageData {
protected $mCSS;
protected $mPHP;
protected $mJS;
protected $mMeta;
protected etc...
}
Each class property contained an array of FragmentBase
instances of a certain data-type to retrieve data from.
But this design isn't very easily maintained and is not very flexible. Also because the object that stored the data is universal, I needed to check the datatype to be able to render it with the correct function.
Is there a way to search through an array of objects fast or should I just stick to using the pageData object
and store my fragment objects
in that?
FragmentBase
objects created to be stored into thepageData
index? So you reuse objects from thepageData
index when you scan the whole HTML page again?