I'm in the process of working on my first code igniter project. I have some javascript that I need to write to initiate an instance of something on document ready. It's a one off, will never be called again. I need to include it in the head, but there may be a case where I need to do this at the end of the body. So, for example, lets say I have this:
<script>
alert('this is a one off alert');
</script>
What is the best practice in doing this stuff? Is it acceptable practice to put this in the controller? Does it need a model writing for it? Or do I need to create individual views for each script to be in MVC?
Thanks.
JS is part of HTML so it should not be in controller or in model, so it should be in view, as you are using framework then you should keep it in a separate file, you can have separate file for each method in your controller or one single JS file each controller.
also you can make a base_controller in your core folder and extend all your controller with it, there you can set all the default JS and CSS. so if you call an index method for a controller it will load with default JS and CSS and if need to add any new just pass it from the controller as John B said
You can have this function in your helper file
/**
* getting js files from public folder
* #param array $js
* #return string
*/
function js_tag($js) {
$out = "";
if (!empty($js)) {
$js = array_reverse($js);
foreach ($js as $j) {
if (strstr($j, "http:") == "" && strstr($j, "https:") == "") {
if ($j == 'tinymac') {
$out.='<script type="text/javascript" src="' . base_url() . 'jscripts/tiny_mce/tiny_mce.js"></script>' . "\n";
} else {
$out.='<script type="text/javascript" src="' . base_url() . 'public/js/' . $j . '"></script>' . "\n";
}
} else {
$out.='<script type="text/javascript" src="' . $j . '"></script>' . "\n";
}
}
}
$out .= '<script type="text/javascript"> var baseurl = "' . base_url() . '"</script>' . "\n";
return $out;
}
/**
* getting css files from public folder
* #author Amir M
* #param array $css
* #return string
*/
function css_tag($css) {
$out = "";
if (!empty($css)) {
$css = array_reverse($css);
foreach ($css as $c) {
if (strstr($c, "http:") == "" && strstr($c, "https:") == "") {
$out.= link_tag(base_url() . "public/css/" . $c) . "\n";
} else {
$out.= link_tag($c) . "\n";
}
}
}
return $out;
}
and you can call it from controller
public function index(){
$data['js'] = js_tag('one.js', 'two.js' , 'jquery.js');
$data['css'] = css_tag('one.css', 'two.css' , 'jquery-ui.css');
$thuis->load->view('index' , $data);
}
Note: the above method will reverse the array so the last value in the array will come first on the page so keep the jQuery last in the array
in the header which is common on all website
<?php echo $js.$css?>
generally the practice I use is this:
All view files load a common header. And the view files are loaded at the end of the controller.
You can either hardcode or pass the links for scripts you want to initiate from the controller. Hardcoding the script tags is self explanatory. If you want to do it a bit more dynamically, you could set up an array of script sources and just loop through them in the header.
so in the controller
$data['scripts'] = array();
$data['scripts'][] = 'http://yoursourcehere';
or if self hosting:
$data['scripts'][] = site_url('assets/js/yourscript.js');
then the view
if(isset($scripts))
{
foreach($scripts as $script)
{
echo '<script type="text/javascript" src="'.$script.'"></script>';
}
}
so basically you can just put all your custom script in a separate file an load it this way. Its practical because it can load all your scripts at once in a common way.
Related
i wanna migrate my website into CI.
i just simply modified from ci sample file welcome.php
in index() function , i load the view to show.
however , i put many javascripts and css files in the header file .
and call it by $this->load->view('header');
but i can not load the javascript files correctly!
Can anyone give me some tips ? it;s hard to configure how to set the correct path.
<script type="text/javascript" src="/assets/javascripts/order.js"></script>
<script type="text/javascript" src="../assets/javascripts/order.js"></script>
<script type="text/javascript" src="../../assets/javascripts/order.js"></script>
my controller code as following
class Welcome extends CI_Controller {
public function index()
{
$this->load->helper('url');
$this->base = $this->config->item('base_url');
$this->load->view('header');
$this->load->view('welcome_message');
}
}
belows are my folder structure
put your assets folder with applications, system, assets
not in application and simple load the url helper class in controller where you call the header view part something like
$this->load->helper('url');
$this->load->view('header');
and simply use something like this in your header file..
because $this->base_url() return the / folder..
<script src="<?php echo $this->base_url();?>assets/javascript/jquery.js"></script>
Changing the folder structure because access within the application folder is just for the core part that i know..
here is the link if you want to know more about URL Helper
This is the best way with minimal code
<script src="<?php echo base_url('assets/javascript/jquery.js');?>"></script>
<script src="<?php echo base_url('assets/css/bootstrap.min.js');?>"></script>
Jogesh_p's answer will surely solve the assets loading problem you have. I would like to follow up on this question you gave
Thank you or your support. btw the way if i wanna use some library
like phpMailler or zend framwork .
You can put in application/libraries/
Then load it in the controller using the Library's Class' Name
$this->load->library('phpmailer');
Its your choice to load in on the constructor or on the individual method.
Good Luck!
To solve my problem I created helper functions to load assets. And here is my code deployed in my application.
PS: First I planned a good/flexible directory structure
[some_helper.php]
/*
* Created: 2017/12/14 00:28:30
* Updated: 2017/12/14 00:28:39
* #params
* $url_structure = 'assets/js/%s.js'
* $files = ['main.min', 'social']
* $echo = FALSE
*
*/
function load_js($files = [], $url_structure = NULL, $version = '1.0', $echo = FALSE){
$html = "";
foreach ($files as $file) {
if($url_structure){
$file = sprintf($url_structure, $file);
}
$file_url = base_url($file);
$html .= "<script src=\"{$file_url}?v={$version}\"></script>";
}
if($echo) {
echo $html;
}
return $html;
}
/*
* Created: 2017/12/14 00:28:48
* Updated: 2017/12/14 00:28:51
* #params
* $version = '1.0' // Later load from configuration
* $url_structure = 'assets/js/%s.css'
* $files = ['main.min', 'social']
* $echo = FALSE
*
*/
function load_css($files = [], $url_structure = NULL, $version = '1.0', $echo = FALSE){
$html = "";
foreach ($files as $file) {
if($url_structure){
$file = sprintf($url_structure, $file);
}
$file_url = base_url($file);
echo "<link rel=\"stylesheet\" href=\"{$file_url}?v={$version}\">";
}
if($echo) {
echo $html;
}
return $html;
}
Then called in the view
[some_view.php]
$css = [
'path' => 'assets/css/%s.css',
'files' => ['bootstrap.min','style']
];
load_css($css['files'], $css['path'], '1.0', TRUE);
Hope it helps someone.
In the case of OP $css['path'] = 'application/assets/css/%s.css'; will do the trick.
Updated the code on Github which I will keep updating.
assets/css/bootstrap.min.css"
<!-- Include JS -->
<script src="<?php echo base_url();?>assets/js/jquery.js"></script>
<script src="<?php echo base_url();?>assets/js/bootstrap.min.js"></script>
function addcategory()
{
//alert("<?php echo base_url();?>")
$.ajax({
complete: function() {}, //Hide spinner
url : '<?php echo base_url();?>category/search',
data:$('#add_category').serialize(),
type : "POST",
dataType : 'json',
success : function(data) {
if(data.code == "200")
{
alert("category added successfully");
}
},
beforeSend: function(XMLHttpRequest){}, //$.blockUI();
cache: false,
error : function(data) {
}
});
}
Following this tutorial http://johnsquibb.com/tutorials/mvc-framework-in-1-hour-part-one Im trying to write my first MVC Blog.
I understood how it works, router.php Calls the suitable page controller. This controller calls the model, Then calls the View page with the returned value.
My question is, What if I want to add to the same news.php page a header\footer. Normally I would write "include("header.php"). But now when using MVC, how could I implement that?
These are my files:
router.php:
<?php
/**
* This controller routes all incoming requests to the appropriate controller
*/
//Automatically includes files containing classes that are called
//fetch the passed request
$pageURL = $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
$path_parts = pathinfo($pageURL);
$page_name = $path_parts['filename'];
$parsed = explode('?' , $page_name);
//the page is the first element
$page = array_shift($parsed);
// If there is any variables, GET them.
if(!empty($parsed))
{
$parsed = explode('&' , $parsed[0]);
$getVars = array();
foreach ($parsed as $argument)
{
//explode GET vars along '=' symbol to separate variable, values
list($variable , $value) = explode('=' , $argument);
$getVars[$variable] = urldecode($value);
}
}
//compute the path to the suitable file
$target ='controllers/' . $page . '_controller.php';
//get target controller
if (file_exists($target))
{
include_once($target);
//modify page to fit naming convention
$class = ucfirst($page) . '_Controller';
//instantiate the appropriate class
if (class_exists($class))
{
$controller = new $class;
}
else
{
//did we name our class correctly?
die('class does not exist!');
}
}
else
{
//can't find the file in 'controllers'!
die('page does not exist!');
}
//once we have the controller instantiated, execute the default function
//pass any GET varaibles to the main method
$controller->main($getVars);
// AutoLoad
function __autoload($className)
{
// Parse out filename where class should be located
// This supports names like 'Example_Model' as well as 'Example_Two_Model'
list($suffix, $filename) = preg_split('/_/', strrev($className), 2);
$filename = strrev($filename);
$suffix = strrev($suffix);
//select the folder where class should be located based on suffix
switch (strtolower($suffix))
{
case 'model':
$folder = '/models/';
$filename = ($className);
break;
case 'library':
$folder = '/libraries/';
break;
case 'driver':
$folder = '/libraries/drivers/';
break;
}
//compose file name
$file = SERVER_ROOT . $folder . strtolower($filename) . '.php';
//fetch file
if (file_exists($file))
{
//get file
include_once($file);
}
else
{
//file does not exist!
die("File '$filename' containing class '$className' not found in
'$folder'.");
}
}
?>
post_controller.php
<?php
/**
* This file handles the retrieval and serving of posts posts
*/
class Posts_Controller
{
/**
* This template variable will hold the 'view' portion of our MVC for this
* controller
*/
public $template = 'posts';
/**
* This is the default function that will be called by router.php
*
* #param array $getVars the GET variables posted to index.php
*/
public function main(array $getVars)
{
//$b_controller =new Bottom_Bar_Controller;
//$b_controller->main($getVars);
$postsModel = new Posts_Model;
//get an post
$post = $postsModel->get_post($getVars['id']);
//create a new view and pass it our template
$header = new View_Model('header_template');
$bottom_bar = new View_Model('bottom_bar');
$view = new View_Model($this->template);
//assign post data to view
$view->assign('header', $header->render(FALSE));
$view->assign('bottom', $bottom_bar->render(FALSE));
$view->assign('title' , $post['title']);
$view->assign('content' , $post['content']);
$view->assign('date' , $post['date']);
$view->assign('by' , $post['added_by']);
$view->render();
}
}
posts_model.php
<?php
/**
* The Posts Model does the back-end heavy lifting for the Posts Controller
*/
class Posts_Model
{
/**
* Holds instance of database connection
*/
private $db;
public function __construct()
{
$this->db = new MysqlImproved_Driver;
}
/**
* Fetches article based on supplied name
*
* #param string $author
*
* #return array $article
*/
public function get_post($id)
{
//connect to database
$this->db->connect();
//sanitize data
$author = $this->db->escape($id);
//prepare query
$this->db->prepare
(
"
SELECT * FROM `posts`
WHERE
`id` = '$id'
LIMIT 1
;
"
);
//execute query
$this->db->query();
$article = $this->db->fetch('array');
return $article;
}
}
?>
view_model.php
<?php
/**
* Handles the view functionality of our MVC framework
*/
class View_Model
{
/**
* Holds variables assigned to template
*/
private $data = array();
/**
* Holds render status of view.
*/
private $render = FALSE;
/**
* Accept a template to load
*/
public function __construct($template)
{
//compose file name
$file = SERVER_ROOT . '/views/' . strtolower($template) . '.php';
if (file_exists($file))
{
/**
* trigger render to include file when this model is destroyed
* if we render it now, we wouldn't be able to assign variables
* to the view!
*/
$this->render = $file;
}
}
/**
* Receives assignments from controller and stores in local data array
*
* #param $variable
* #param $value
*/
public function assign($variable , $value)
{
$this->data[$variable] = $value;
}
/**
* Render the output directly to the page, or optionally, return the
* generated output to caller.
*
* #param $direct_output Set to any non-TRUE value to have the
* output returned rather than displayed directly.
*/
public function render($direct_output = TRUE)
{
// Turn output buffering on, capturing all output
if ($direct_output !== TRUE)
{
ob_start();
}
// Parse data variables into local variables
$data = $this->data;
// Get template
include($this->render);
// Get the contents of the buffer and return it
if ($direct_output !== TRUE)
{
return ob_get_clean();
}
}
public function __destruct()
{
}
}
posts.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="../style/style.css" rel="stylesheet" type="text/css" media="screen" />
<title> Posts (View)</title>
</head>
<body>
<div id="main">
<div class="container">
<?=$data['header'];?>
<div id="content">
<div class="content-background">
<h2> <?=$data['title'];?></h2>
<h4> <?=$data['date'];?> </h4>
<p><?=$data['content'];?></p>
</div>
</div>
</div>
</div>
</body>
</html>
Part of the problem is, that your tutorial has a pretty primitive interpretation of MVC-inspired design pattern (you actually cannot implement classical MVC in PHP, but there are patterns, that are based on it).
View is not just a template. Views are supposed to be class instances, which contain all presentation logic and deal with multiple templates. What you actually have there is a layout template which contains posts template.
// class \Application\View\Posts
public function render()
{
$layout = new Template( $this->defaultTemplateDirectory . 'layout.html');
$content = new Template( $this->defaultTemplateDirectory . 'posts.html' );
$layout->assign( 'content' , $content->render() );
return $layout->render();
}
Also, one of the things, that a view instance should do, is requesting information from the model layer.
Few materials that you might find useful:
Model-View-Confusion part 1: Why the model is accessed by the view in MVC
Simple PHP Template Engine
How should a model be structured in MVC?
And if you want to expand you knowledge in OOP, this post contains a list of recommended lectures and books.
There is no good solution in the MVC structure for that. You can find a solution in every framework. In CakePHP for example you can use an AppController, a controller which is always called for every requests. Sort of base controller.
But no, not very nice to do.
Most simple one is to ask the data directly from the view. That sounds weird but it is accepted in the MVC structure. So in your view you call $News->getLatestItems(10); and work with them.
I don't like it but it works.
If you have lots of widgets and blocks MVC alone might just not be the right structure. Then you could take a look at things like: http://techportal.inviqa.com/2010/02/22/scaling-web-applications-with-hmvc/ which is a derivate of MVC.
Another solution which you see more and more: Request it via AJAX calls. So just load them after the page has loaded. That way you also solve the issue since one MVC request then becomes multiple MVC requests.
Studying some code from a codeigniter tut, the following preg_match pattern has me baffled:
preg_match('/js$/', $include)
What is the purpose of the $ after the js?
Thanks for the always thoughtful replies!
-----Complete Code-----
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Layouts Class. PHP5 only.
*
*/
class Layouts {
// Will hold a CodeIgniter instance
private $CI;
// Will hold a title for the page, NULL by default
private $title_for_layout = NULL;
// The title separator, ' | ' by default
private $title_separator = ' | ';
public function __construct()
{
$this->CI =& get_instance();
}
public function set_title($title)
{
$this->title_for_layout = $title;
}
public function view($view_name, $params = array(), $layout = 'default')
{
// Handle the site's title. If NULL, don't add anything. If not, add a
// separator and append the title.
if ($this->title_for_layout !== NULL)
{
$separated_title_for_layout = $this->title_separator . $this->title_for_layout;
}
// Load the view's content, with the params passed
$view_content = $this->CI->load->view($view_name, $params, TRUE);
// Now load the layout, and pass the view we just rendered
$this->CI->load->view('laytous/' . $layout, array(
'content_for_layout' => $view_content,
'title_for_layout' => $separated_title_for_layout
));
}
public function add_include($path, $prepend_base_url = TRUE)
{
if ($prepend_base_url)
{
$this->CI->load->helper('url'); // Load this just to be sure
$this->file_includes[] = base_url() . $path;
}
else
{
$this->file_includes[] = $path;
}
return $this; // This allows chain-methods
}
public function print_includes()
{
// Initialize a string that will hold all includes
$final_includes = '';
foreach ($this->includes as $include)
{
// Check if it's a JS or a CSS file
if (preg_match('/js$/', $include))
{
// It's a JS file
$final_includes .= '<script type="text/javascript" src="' . $include . '"></script>';
}
elseif (preg_match('/css$/', $include))
{
// It's a CSS file
$final_includes .= '<link href="' . $include . '" rel="stylesheet" type="text/css" />';
}
return $final_includes;
}
}
}
The dollar is an "end of string" anchor. The match will only succeed if "js" is at the end of the string.
Dollar sign means an end of line in regular expressions.
Alright, I'm using a page creating class I found as below but when I want to use a php page -that again includes and uses a class file- for the content it either echoes on the top or the bottom of the page... I even tried to make the page a function() and call it at the $Content string but no use, again it echoed on the top of the page... How can i use a php page as a content in this class, or what should i change to use a php file?
Please keep in mind that I'm new to classes so feel free to assume some beginner mistakes.
<?php
class Page {
var $Title;
var $Keywords;
var $Content;
function Display( ) {
echo "<HTML>\n<HEAD>\n";
$this->DisplayTitle( );
$this->DisplayKeywords( );
echo "\n</HEAD>\n<BODY>\n";
echo $this->Content;
echo "\n</BODY>\n</HTML>\n";
}
function DisplayTitle( ) {
echo "<TITLE>" . $this->Title . "</TITLE>\n";
}
function DisplayKeywords( ) {
echo '<META NAME="keywords" CONTENT="' . $this->Keywords . '">';
}
function SetContent( $Data ) {
$this->Content = $Data;
}
}
?>
Usage:
<?php
include "page.class";
$Sample = new Page;
$Content = "<P>I want my php file's contents here.</P>";
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent( $Content );
$Sample->Display( );
?>
What if I wanted to make the content something like $Content = " < ? echo 'test'; ? >"; I know this isn't valid but what i'm trying to do is something like that or something like $Content = " output of the whateversinhere.php ";. how should I object orient another page therefore getting its contents into a string here?
You should NOT echo anything inside your class, instead the class should have a method getMarkup(), which will return a string containing the whole markup. Then you can echo that string in your view.
Additional tipps:
variables and method names start with a small letter!
title and keywords should have getters and setters too
make your variables private (private $title, etc.)
let me clean this up for you, you will notice some changes:
class Page
{
private $title = 'No Title';
private $keywords = array();
private $content = '';
public function setTitle($title)
{
$this->title = (string)$title;
}
public function addKeywords($keywords)
{
$this->keywords = array_merge($this->keywords, (func_num_args() > 1) ? func_get_args() : (array)$keywords;
}
function setContent($content)
{
$this->content = $content;
}
function appendContent($content)
{
$this->content .= $content;
}
function prependContent($content)
{
$this->content = $content . $this->content;;
}
private function display()
{
/*
* Display output here
*/
echo $this->title;
echo implode(',',str_replace(',','',$this->title));
echo $this->contents;
}
}
pretty simple usage:
$Page = new Page;
$Page->setTitle("Hello World");
$page->addKeywords("keyword1","keyword2","keyword3","keyword4");
//Content
$this->setContent("World");
$this->prependContent("Hello");
$this->appendContent(".");
//Display
$this->display();
Just got to fill in the blanks, you will learn as time goes on that you should not be using html directly within your class, and that you would split the above into several class such as Head,Body,Footer,Doctype and have a page class that brings them all together.
Use Output Control Functions.
<?php
include "page.class";
$Sample = new Page;
ob_start();
include "foobar.php";//What you want to include.
$content = ob_get_contents();
ob_end_clean();
$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->SetContent($content);
$Sample->Display( );
?>
So I'm setting up a system that has a lot of emails, and variable replacement within it, so I'm writing a class to manage some variable replacement for templates stored in the database.
Here's a brief example:
// template is stored in db, so that's how this would get loaded in
$template = "Hello, %customer_name%, thank you for contacting %website_name%";
// The array of replacements is built manually and passed to the class
// with actual values being called from db
$replacements = array('%customer_name%'=>'Bob', '%website_name%'=>'Acme');
$rendered = str_replace(array_keys($replacements), $replacements, $template);
Now, that works well and good for single var replacements, basic stuff. However, there are some places where there should be a for loop, and I'm lost how to implement it.
The idea is there'd be a template like this:
"hello, %customer_name%, thank you for
requesting information on {products}"
Where, {products} would be an array passed to the template, which the is looped over for products requested, with a format like:
Our product %product_name% has a cost
of %product_price%. Learn more at
%product_url%.
So an example rendered version of this would be:
"hello, bob, thank you for requesting
information on:
Our product WidgetA has a cost of $1.
Learn more at example/A
Our product WidgetB has a cost of $2.
Learn more at example/B
Our product WidgetC has a cost of $3.
Learn more at example/C.
What's the best way to accomplish this?
Well, I really dont see the point in a template engine that uses repalcements/regex
PHP Is already a template engine, when you write <?php echo $var?> its just like doing <{$var}> or {$var}
Think of it this way, PHP Already translates <?php echo '<b>hello</b>'?> into <b>hello</b> by its engine, so why make it do everything 2 times over.
The way i would implement a template engine is like so
Firstly create a template class
class Template
{
var $vars = array();
function __set($key,$val)
{
$this->vars[$key] = $val;
}
function __get($key)
{
return isset($this->vars[$key]) ? $this->vars[$key] : false;
}
function output($tpl = false)
{
if($tpl === false)
{
die('No template file selected in Template::output(...)');
}
if(!file_exists(($dir = 'templates/' . $tpl . '.php')))
{
die(sprintf('Tpl file does not exists (%s)',$dir));
}
new TemplateLoader($dir,$this->vars);
return true;
}
}
This is what you use in your login such as index.php, you will set data just like an stdClass just google it if your unsure. and when you run the output command it sends the data and tpl to the next class below.
And then create a standalone class to compile the tpl file within.
class TemplateLoader
{
private $vars = array();
private $_vars = array(); //hold vars set within the tpl file
function __construct($file,$variables)
{
$this->vars = $variables;
//Start the capture;
ob_start();
include $file;
$contents = ob_get_contents();
ob_end_clean(); //Clean it
//Return here if you wish
echo $contents;
}
function __get($key)
{
return isset($this->vars[$key]) ? $this->vars[$key] : (isset($this->_vars[$key]) ? $this->_vars[$key] : false) : false;
}
function __set($key,$val)
{
$this->_vars[$key] = $val;
return true;
}
function bold($key)
{
return '<strong>' . $this->$key . '</string>';
}
}
The reason we keep this seperate is so it has its own space to run in, you just load your tpl file as an include in your constructor so it only can be loaded once, then when the file is included it has access to all the data and methods within TemplateLoader.
Index.php
<?php
require_once 'includes/Template.php';
require_once 'includes/TemplateLoader.php';
$Template = new Template();
$Template->foo = 'somestring';
$Template->bar = array('some' => 'array');
$Template->zed = new stdClass(); // Showing Objects
$Template->output('index'); // loads templates/index.php
?>
Now here we dont really want to mix html with this page because by seperating the php and the view / templates you making sure all your php has completed because when you send html or use html it stops certain aspects of your script from running.
templates/index.php
header
<h1><?php $this->foo;?></h1>
<ul>
<?php foreach($this->bar as $this->_foo):?>
<li><?php echo $this->_foo; ?></li>
<?php endforeach; ?>
</ul>
<p>Testing Objects</p>
<?php $this->sidebar = $this->foo->show_sidebar ? $this->foo->show_sidebar : false;?>
<?php if($this->sidebar):?>
Showing my sidebar.
<?php endif;?>
footer
Now here we can see that were mixing html with php but this is ok because in ehre you should only use basic stuff such as Foreach,For etc. and Variables.
NOTE: IN the TemplateLoader Class you can add a function like..
function bold($key)
{
return '<strong>' . $this->$key . '</string>';
}
This will allow you to increase your actions in your templates so bold,italic,atuoloop,css_secure,stripslashs..
You still have all the normal tools such as stripslashes/htmlentites etc.
Heres a small example of the bold.
$this->bold('foo'); //Returns <strong>somestring</string>
You can add lots of tools into the TempalteLoader class such as inc() to load other tpl files, you can develop a helper system so you can go $this->helpers->jquery->googleSource
If you have any more questions feel free to ask me.
----------
An example of storing in your database.
<?php
if(false != ($data = mysql_query('SELECT * FROM tpl_catch where item_name = \'index\' AND item_save_time > '.time() - 3600 .' LIMIT 1 ORDER BY item_save_time DESC')))
{
if(myslq_num_rows($data) > 0)
{
$row = mysql_fetch_assc($data);
die($row[0]['item_content']);
}else
{
//Compile it with the sample code in first section (index.php)
//Followed by inserting it into the database
then print out the content.
}
}
?>
If you wish to store your tpl files including PHP then that's not a problem, within Template where you passing in the tpl file name just search db instead of the filesystem
$products = array('...');
function parse_products($matches)
{
global $products;
$str = '';
foreach($products as $product) {
$str .= str_replace('%product_name%', $product, $matches[1]); // $matches[1] is whatever is between {products} and {/products}
}
return $str;
}
$str = preg_replace_callback('#\{products}(.*)\{/products}#s', 'parse_products', $str);
The idea is to find string between {products} and {products}, pass it to some function, do whatever you need to do with it, iterating over $products array.
Whatever the function returns replaces whole "{products}[anything here]{/products}".
The input string would look like that:
Requested products: {products}%product_name%{/products}