PHP - Custom Template Class
hello,
I have tried to build a website on codeigniter, then i thought I shouldn't use a framework because then I would learn php better. And heres a problem: on codeigniter, to load a template file all I had to do was write this line $this -> load -> view ( 'somefile.php' ); now when i can't use this, i googled for some php template classes/engines, and didn't find any like codeigniter had. I want to load the file like $this -> load ( 'file.php' ); or similar, because now I have to write much more lines and it's pretty confusing ( $template = new Template ( 'file.php' ); the operations with it, and if my header/footer is separated from main content it gets pretty messy.). Can anyone help me to write my own template class? Sorry for bad English... Similar TutorialsHey guys,
Wordpress has the ability to recognize a custom page and make it available to select it and use when you are logged in in the pages section of the admin ui. To make it work you add this:
<?php /* * Template Name: My Custom Page * Description: A Page Template with a darker design. */ // Code to display Page goes here...My question is how does wordpress scan and find these files and then show them in a drop down menu on the pages tab of the admin? Is it done with regular expressions? Many thanks for any help! Hi all, I created a page template at http://www.durgeshsound.com/gallery/ Here my pagination buttons are not working. this issue arises when permalink format is http://www.example.com/sample-post/ But when I set permalink format to default (www.example.com/?p=123) then it starts to work and creates a working pagination link like this http://www.durgeshso...e_id=81&paged=2. I want this format http://www.example.com/sample-post/ in the links. Please help. im trying to make a simple template engine but am having a problem replacing the string in the content....if anyone could give me any help or pointers please <?php class Template { public function display($filename) { echo "hello"; } public function assign($variable, $value) { if (!is_array($value)) { ob_start(); $contents = ob_get_contents(); $contents = str_replace($variable, $value, $contents); ob_end_clean(); return $contents; } } } $template = new Template(); $template->display(); $template->assign("hello", "test"); ?> code above will only display hello and not test as it should Well i have this set of codes <?php include "includes/config.php"; class template{ var $page; var $built; public $block = array(); function _start($tpl){ $this->page = $tpl; } function set_array($data){ $this->block[] = $data; } function _show(){ foreach($this->block as $k => $v){ foreach($v as $k1 => $v1){ //echo $k1."<br />"; //echo $v1."<br />"; $this->page = str_replace("{".$k1."}", $v1, $this->page); } } echo $this->page; } } $template = new template(); $file = "<html> <body> <p>{CAT}</p> <p>{SUBCAT}</p> </body> </html>"; $template->_start($file); // Category Query while($row1 = mysql_fetch_assoc($cat)){ $template->set_array(array("CAT" => $row1['title'])); // Sub Category Query while($row2 = mysql_fetch_assoc($subcat)){ $template->set_array(array("SUBCAT" => $row2['title'])); } } $template->_show(); ?> Now, when i echo $k1 or $v1 they display the keys and values in the correct order like CAT1 SUBCAT1.1 SUBCAT1.2 CAT2 SUBCAT2.1 SUBCAT2.2 but when it goes through the str_replace its only displays the CAT1 and SUBCAT1.2 what going wrong? So I made a template class, it's very simple, pretty much allows the usage like so: $template = new template("blogpost"); $template->fillBraces(array( "TITLE" => "How to bathe your chimpanzee", "AUTHOR" => "Jim Bo James" )); $template->render(); Simple, uses tpl files, similar to what phpbb used a long time back, not sure if they still do. My main goal for this is to have a file that has something like this: {HEADER} {MAIN_CONTENT} {FOOTER} and the above usage to stay the same, however that would fill the main_content part, and the header and footer would be grabbed from header/footer tpl files. Any idea on suggestions? The full class is posted below. class template { protected $_viewContents; function __construct($viewName) { $this->_viewContents = file_get_contents(TEMPLATE.$viewName.TEMPLATE_EXT); return; } function sourceOf($fileName) { return @file_get_contents(TEMPLATE.$fileName.TEMPLATE_EXT); } function fillLayout() { } function fillBraces($information, $replacement=NULL) { if (is_array($information)) { foreach ($information as $key => $val) { $this->_viewContents = str_ireplace("{".$key."}", $val, $this->_viewContents); } return; } elseif ($replacement!=NULL) { $this->_viewContents = str_ireplace("{".$information."}", $replacement, $this->_viewContents); return; } } function render() { echo $this->_viewContents; } } Thanks! I've searched all over for the past few days trying to figure out what I'm doing wrong. Basically what I'm trying to do is create a prepared statement inside my User class. I can connect to the database, but my query does not execute as expected. Here's the code for my User class Code: [Select] <?php include '../includes/Constants.php'; ?> <?php /** * Description of User * * @author Eric Evas */ class User { var $id, $fname, $lname, $email, $username, $password, $conf_pass; protected static $db_conn; //declare variables public function __construct() { $host = DB_HOST; $user = DB_USER; $pass = DB_PASS; $db = DB_NAME; //Connect to database $this->db_conn = new mysqli($host, $user, $pass, $db); //Check database connection if ($this->db_conn->connect_error) { echo 'Connection Fail: ' . mysqli_connect_error(); } else { echo 'Connected'; } } function regUser($fname, $lname, $email, $username, $password, $conf_pass) { if ($stmt = $this->db_conn->prepare("INSERT INTO USERS (user_fname,user_lname, user_email,username,user_pass) VALUES (?,?,?,?,?)")) { $stmt->bind_param('sssss', $this->fname, $this->lname, $this->email, $this->username, $this->password); $stmt->execute(); $stmt->store_result(); $stmt->close(); } } } ?> And here's the file that I created to instantiate an instance of the user class. Code: [Select] <?php include_once 'User.php'; ?> <?php //Creating new User Object $newUser = new User(); $newUser->fname = $_POST['fname']; $newUser->lname = $_POST['lname']; $newUser->email = $_POST['email']; $newUser->username = $_POST['username']; $newUser->password = $_POST['password']; $newUser->conf_pass = $_POST['conf_pass']; $newUser->regUser($newUser->fname, $newUser->lname, $newUser->email, $newUser->username, $newUser->password, $newUser->conf_pass); ?> And lastly heres the form that I want to get info from the user to insert into the database Code: [Select] <html> <head> <title></title> <link href="stylesheets/styles.css" rel="stylesheet" type="text/css"/> </head> <body> <form action = "Resources/testClass.php" method="post" enctype="multipart/form-data"> <label>First Name: </label> <input type="text" name="fname" id="fname" size="25" maxlength="25"/> <label>Last Name: </label> <input type="text" name="lname" id="lname" size="25" maxlength="25"/> <label>Email: </label> <input type="text" name="email" id="email" size="25" maxlength="40"/> <label>Username: </label> <input type="text" name="username" id="username" size="25" maxlength="32"/> <label>Password: </label> <input type="password" name="password" id="password" size="25" maxlength="32"/> <label>Re-enter Password: </label> <input type="password" name="conf_pass" id="conf_pass" size="25" maxlength="32"/> <br /><br /> <input type="submit" name="submit" id="submit" value="Register"/> <input type="reset" name="reset" id="reset" value="Reset"/> </form> </body> </html> I'm sure it's not much, but I'm not understanding something with custom error handlers: I've created a custom error handler, which I initially set when my page loads : set_error_handler(array ( new ErrorHandler(), 'handleError' ));
It seems to catch all internal PHP errors, such as if I: var_dump($non_existing_var); right after the set_error_handler.... Now, I have an object that throws an exception after: set_error_handler(array ( new ErrorHandler(), 'handleError' )); $locale = new \CorbeauPerdu\i18n\Locale(...); // this should throw an exception ... I thought that with an error handler set, I could 'skip' the try/catch for it, but doing so, PHP spits out in its internal log: PHP Fatal error: Uncaught CorbeauPerdu\i18n\LocaleException: ....
My error handler doesn't catch it at all before, thus my page breaks!! If I want it to go through the error handler, I have to init my Locale with a try/catch and use trigger_error() like so: set_error_handler(array ( new ErrorHandler(), 'handleError' )); try { $locale = new \CorbeauPerdu\i18n\Locale(...); // this should throw an exception } catch(Exception $e) { trigger_error($e->getMessage(), E_USER_ERROR); } ... Is this normal ? I thought one of the goals of the error_handler was to catch anything that wasn't dealt with? Thanks for your answers! I have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me Hi Can you call Class A's methods or properties from Class B's methods? Thanks. I have an existing instance of my class Database, now I want to call that instance in my Session class, how would I go about doing this? Ok. I know you can pass the object of a class as an argument. Example: class A { function test() { echo "This is TEST from class A"; } } class B { function __construct( $obj ) { $this->a = $obj; } function test() { $this->a->test(); } } Then you could do: $a = new A(); $b = new B($a); Ok so that's one way i know of. I also thought that you could make a method static, and do this: (assuming class A's test is 'static') class B { function test() { A::test(); } } But that is not working. I'd like to know all possible ways of accomplishing this. Any hints are appreciated. thanks If a class has a constructor but also has a static method, if I call the static method does the constructor run so that I can use an output from the constructor in my static method? --Kenoli Hi, I need to be able to call a class based on variables. E.G. I would normally do: Code: [Select] $action = new pattern1() but i would like to be able to do it dynamicaly: Code: [Select] $patNum = 1; $action = new pattern.$patNum.() Im wondering if that's possible? If so what would the correct syntax be? Many Thanks. Hi people! class FirstOne{ public function FunctionOne($FirstInput){ //do stuff and output value return $value1; } } Then:- class SecondOne{ public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } } What I want to know is this, if I want to use FunctionOne() in Class SecondOne do I do it like this:- (Assume as I have instantiated the first class using $Test = new FirstOne(); ) class SecondOne{ function SecondedFunction(){ global $Test; return $Test->FunctionOne(); } public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } public function FunctionThree(){ //some code here $this->Test->SecondedFunction();<--I think as I can omit the $this-> reference } } My point is: Do I have to do it this way or is there way of having this done through __construct() that would negate the need for a third party function? I have a version working, I just think that it is a little convoluted in the way as I have done it, so I thought I would ask you guys. Any help/advice is appreciated. Cheers Rw I have two classes: ## Admin.php <?php class Admin { public function __construct() { include("Config.php"); } /** * deletes a client * @returns true or false */ function deleteClient($id) { return mysql_query("DELETE FROM usernames WHERE id = '$id'"); } } ?> ## Projects.php <?php class Projects { public function __construct() { include("Config.php"); $this->admin = $admin; $this->dataFolder = $dataFolder; } /** * Deletes a project * @returns true or false */ function deleteProject($id) { $root = $_SERVER['DOCUMENT_ROOT']; $theDir = $root . $this->dataFolder; $sql = mysql_query("SELECT * FROM projectData WHERE proj_id = '$id'"); while ($row = mysql_fetch_array($sql)) { $mainFile = $row['path']; $thumb = $row['thumbnail']; if ($thumb != 'null') { unlink($theDir . "/" . substr($thumb,13)); } unlink($theDir . "/" . substr($mainFile,13)); } $delete = mysql_query("DELETE FROM projectData WHERE proj_id = '$id'"); $getDir = mysql_query("SELECT proj_path FROM projects WHERE id = '$id'"); $res = mysql_fetch_array($getDir); rmdir($theDir . "/" . $res['proj_path']); return mysql_query("DELETE FROM projects WHERE id = '$id'"); } } ?> How can I call deleteProject() from within Admin.php? Hi all, I have two classes. Registration and Connection. Inside a registration.php I include my header.php, which then includes my connection.php... So all the classes should be declared when the page is loaded. This is my code: registration.php: <?php include ('assets/header.php'); ?> <?php class registration{ public $fields = array("username", "email", "password"); public $data = array(); public $table = "users"; public $dateTime = ""; public $datePos = 0; public $dateEntryName = "date"; function timeStamp(){ return($this->dateTime = date("Y-m-d H:i:s")); } function insertRow($data, $table){ foreach($this->fields as $key => $value){ mysql_query("INSERT INTO graphs ($this->fields) VALUES ('$data[$key]')"); } mysql_close($connection->connect); } function validateFields(){ $connection = new connection(); $connection->connect(); foreach($this->fields as $key => $value){ array_push($this->data, $_POST[$this->fields[$key]]); } $this->dateTime = $this->timeStamp(); array_unshift($this->data, $this->dateTime); array_unshift($this->fields, $this->dateEntryName); foreach($this->data as $value){ echo "$value"; } $this->insertRow($this->data, $this->table); } } $registration = new registration(); $registration->validateFields(); ?> <?php include ('assets/footer.php'); ?> At this point I cannot find my connection class defined on another included/included page. $connection = new connection(); $connection->connect; config.php (included within header.php) <? class connection{ public $dbname = '**'; public $dbHost = '**'; public $dbUser = '**'; public $dbPass = '**'; public $connect; function connect(){ $this->connect = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die ('Error connecting to mysql'); mysql_select_db($this->dbname, $this->connect); } } ?> Any ideas how to call it properly? I have a class in which I have a function called connection. I am now trying to call this function from another class, but it will not work. It works if I put the code in from the other function rather than calling it but that defeats the purpous. class locationbox { function location() { $databaseconnect = new databaseconnect(); $databaseconnect -> connection();{ $result = mysql_query("SELECT * FROM locations"); while($row = mysql_fetch_array($result)) // line that now gets the error, mysql_fetch_array() expects parameter 1 to be resource, boolean given //in { echo "<option>" . $row['location'] . "</option>"; } } }} I do know how to do this but I am curious about whether or not there is a "preferred" way to do this. I know there are a couple ways to use a class (I'll call Alpha_Class) within another class (I'll class Beta_Class) Let's say we have this simple class (Beta_Class): class beta { function foo(){ } } If I wanted to use the Alpha Class within the Beta Class, I could any number of things. For example: class beta { function foo(){ $this->alpha = new alpha; //$this->alpha->bar(); } } Or you could simply use the $GLOBALS array to store instantiated objects in: $GLOBALS['alpha'] = new alpha; class beta { function foo(){ //GLOBALS['alpha']->bar(); } } You could even declare Alpha_Class as a static class and thus would not need to be instantiated: static class alpha { static function bar(){} } class beta { function foo(){ //alpha::bar(); } } Those are the only ways I can think of right now. Are there any other ways to accomplish this? I was wondering which way is the best in terms of readability and maintainability. How does one go about using one class inside another? For example, building a class that does some series of functions, and uses a db abstraction layer class in the process? |