PHP - Made Template Class, How To Incorporate Into Overall Layout?
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! Similar TutorialsHi I made a new design for my website and I made some changes. I want to use layout for my second site.
I'll like to know if my site is easier to browse through now and if you like the design better?. I test my site on internet explorer, chrome, and firefox. It is best to use site on better browsers like firefox and chrome to get a better experience of site. Thanks.
http://adjade.com
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... 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? I've made a template system, but the way I've chosed to do it doesn't give me the ability to choose a design. I've posted the code below with a bad solution for my design problem. Does anyone have any suggestions how to make a very simple and smart templatesystem? I don't have any problems coding. I just need ideas :-) Code: [Select] <?php final class View implements IView { protected $filename, $variables = array(); public function __construct($filename = null, $variables = array()) { $this->filename = $filename; $this->variables = $variables; } public function __toString() { if(!file_exists($this->filename)) { throw new Exception("View does not exists."); } $content = file_get_contents($this->filename); foreach($this->variables as $variable => $value) { $content = str_replace("#{{$variable}}", $value, $content); } return str_replace("#{content}", $content, file_get_contents("design.html")); } } ?> Since I got my websocket PHP server running nicely with my MYSQL, I can now have some fun
Attack speed is very simple, but I need your help with the unixtimestamp.
For example, There is a field name called "last_attack" and each time a user attacks a mob and a skill was performed; it will be updated with:
time();Then I disable the attack button for 2 seconds client side, but I also check that value against time() serverside as well. Now let's say the user's attack speed is 1.30% I want to make that Attack Speed check, to check it dynamically. It should now check only if the attack was less than 1.7 seconds ago instead of 2 seconds. How do I split up the unixtimestamp to work with percents? Edited by Monkuar, 03 December 2014 - 02:11 PM. hello all, i have ran into another issue i get this message when i go onto my homepage Notice: Undefined variable: layout in i have the following includes on the main index page: Code: [Select] <?php // Include Main Core File. include '_class/core.php'; // Include Config File include 'config/config.php'; include 'config/db.php'; // Use Database $obj->connect(); // Include library include '_class/library.php'; // Include layout include 'layout/index.php'; ?> on the config file i have the varible it is refering too: Code: [Select] <?php $layout = $url . "layout/"; ?> the actual file i get the error on (library.php) Code: [Select] <?php class library extends core { function advert() { /* * Name your images 1.jpg, 2.jpg etc. * * Add this line to your page where you want the images to * appear: <?php include "randomimage.php"; ?> */ // Change this to the total number of images in the folder $total = "2"; // Change to the type of files to use eg. .jpg or .gif $file_type = ".png"; // Change to the location of the folder containing the images $image_folder = $layout . "layout/images/adverts"; // You do not need to edit below this line $start = "1"; $random = mt_rand($start, $total); $image_name = $random . $file_type; echo "<img src=\"$image_folder/$image_name\" alt=\"$image_name\" />"; } } $obj = new library; ?> is there a way to make it so it $layout works on any page or file as long as its in the includes? thanks again. Hi! I have started a big project with some of my friends. Its some kind of CMS system. Now, for quick commands we wanted something like cmd on windows. Is it possible to build a script that would be something like cmd/a console. Of course it would be a webpage and not a separate window. I could do this myself with a input field and a form using the POST method. But I wouldn't wan't to refresh the page every time I run a command. So something that works like the input field, form with the POST method, but without needing to refresh every time. Ask if I didn't make it clear enough! Regards Kevin
hello i am learning php a newbie .
// this is the user input / textdata
if(isset($_POST['textdata']))
// i added this line
// i changed this line below
fwrite($fp, $data);
thank you in advance. Edited November 21, 2019 by thehubclickleft out info Hey guys basically with a simple script that I made I need some help with it's doing my head in. What i'm trying to do is allow multiple filetypes to be shown by readdir, i want both .zip and .rar to be in the list, not just .zip how would i add .rar in this method as well to be visible on readdir? <?php $dirname = "/home/test/"; $dir = opendir($dirname); $extension = array_pop(explode(".", $file)); ?> <?php while(false != ($file = readdir($dir))) { if ($file != "." && $file != ".." && array_pop(explode(".", $file)) == "zip") { echo(" <b>» <a href='$dirname$file'>$file - Download</a> <br /> </b> "); } } ?> Hi all, I was playing a bit around with results from a database and thought lets give them a nice order in a table, so i thought i set the class per row, so my style sheet can finish it. This is what i got and it works. But some 6th sense whispers me that this can be done smoother. If anyone has ideas or tips let me know i have a lot to learn in php. and after all want to be a good code writer in php. // start table echo '<table class="users"> <th>name</th><th>email</th><th>active</th>'; $odd = 1; $num = 1; while($row = mysqli_fetch_assoc($result)){ // if( $odd == $num%2 ){ $evenodd = 'odd'; $num++; }else{ $evenodd = 'even'; $num++; } // echo'<tr class="'.$evenodd.'"><td>'.$row['name'].'</td><td>'.$row['email'].'</td><td>'.$row['accept'].'</td><tr>'; } echo '</table>'; thanks so I am about to start on a small object oriented project, for practice/learning etc. I have 5 files in a folder called "objects" : (obj1.php obj2.php obj3.php obj4.php obj5.php) . I then created a "classloader.php" with the following code: Code: [Select] <?php include "objects/obj1.php"; include "objects/obj2.php"; include "objects/obj3.php"; include "objects/obj4.php"; include "objects/obj5.php"; ?> and then finally my main page (for the sake of testing): Code: [Select] <!DOCTYPE HTML> <head> <title>...</title> </head> <?php include "classloader.php"; ?> <body> <header></header> <nav></nav> <section> <?php object1(); object2(); object3(); object4(); object5(); ?> </section> <footer></footer> </body> What is the best way to handle the loading of objects in php? I think I am doing it somewhat wrong. Anyone lend me some more info here? thanks much. Hello everyone For a site of one of our customers our programmer created his own CMS which works OK at the site, but now the customer wants to shorten the URLS which are generated by the system. Is this easily possible? The programmer doesn't have the time to help us with it so that's why I try my luck here... I hope somebody can help me. Thanks! I have this query that fully works the way it is, but I am wondering if I am overdoing some things in it. I know this may be hard to tell without knowing the full relationship between all the tables in the query. I'm basically running 3 subqueries mostly based on a timestamp value and other specific clauses per subquery. Where the main query is only gathering based on the timestamp.
Like I said it works perfect from what I can verify by cross referencing the tables manually and checking the results the query returned. I just want to know if there is a better way to do all this.
SELECT `products`.`id` AS `pid`, `products`.`prod_name`, (SELECT COUNT(*) FROM `products` INNER JOIN `quote_deposits` ON `quote_deposits`.`product_id` = `products`.`id` INNER JOIN `quote_responses` ON `quote_responses`.`id` = `quote_deposits`.`q_id` WHERE `quote_responses`.`purchased` = 0 AND `quote_deposits`.`dep_date` >= $committed_start ) AS `committed`, (SELECT COUNT(`products`.`id`) FROM `products` INNER JOIN `quote_deposits` ON `quote_deposits`.`product_id` = `products`.`id` INNER JOIN `quote_responses` ON `quote_responses`.`id` = `quote_deposits`.`q_id` WHERE `quote_responses`.`purchased` = 1 AND `products`.`id` = `pid` AND `quote_deposits`.`dep_date` >= $committed_start ) AS `total_per_item`, (SELECT COUNT(`products`.`id`) FROM `products` INNER JOIN `quote_deposits` ON `quote_deposits`.`product_id` = `products`.`id` INNER JOIN `quote_responses` ON `quote_responses`.`id` = `quote_deposits`.`q_id` INNER JOIN `schedule` ON `schedule`.`deposit_id` = `quote_deposits`.`id` WHERE `quote_responses`.`purchased` = 0 AND `schedule`.`cancelled` != '' AND `products`.`id` = `pid` AND `quote_deposits`.`dep_date` >= $committed_start ) AS `total_cancelled` FROM `products` INNER JOIN `quote_deposits` ON `quote_deposits`.`product_id` = `products`.`id` WHERE `quote_deposits`.`dep_date` >= $committed_start GROUP BY `products`.`prod_name` ORDER BY `products`.`prod_name` ASC Hi, I have a form with a submit button (Delete button). after I click the button I do few changes in database. Problem is that in this form, after the submit made, it still shows me old data that deleted.... So, I guess I need somehow to make a page refresh through a GET method. How do I do this? Thank u! Hello, Where can i find the source of the pre made php functions? Greets, Scuar.
Hello people! Well, I'm working on a site that has a financing simulator that asks for your data and a value related to cars, real estate and motorcycles. When simulating, it sends you to a page, calculating the closest result and sends your data to the database. However, he has a problem now. When you try to simulate, it no longer shows the result, it even loads the table but has no content, and the simulator form quickly pops up again. Check out an example at http://vitorconsorcios.com.br/simulador.php, below has the source code of the site. I've tried everything, but this is my last solution. What could be the cause of this? <?php include("injection.php"); /* if (isset($_POST['valorcon']) */ $valorcon = (int) tira_virgula_para_ponto( $_POST['valorcon'] ); $plano=anti_injection($_POST["plano"]); $tipo=anti_injection($_POST["tipo"]); $nomecon=anti_injection($_POST["nomecon"]); $telefone=anti_injection($_POST["telefone"]); $emailcon=anti_injection($_POST["emailcon"]); $cidadecon=anti_injection($_POST["cidadecon"]); if ($valorcon>0) { // Inseri a procura $tsql = " insert simulacao set plano='$plano' , tipo = '$tipo' , valor = $valorcon , nome = '$nomecon' , telefone = '$telefone' , email = '$emailcon' , cidade = '$cidadecon' "; //echo $tsql; //exit; $sql_insert = fbd($tsql,"","inserir simulacao"); ?> <div class="col-md-5"> <img src="img/simule.jpg" class="imagem" alt="Vitor Consórcios"> </div> <div class="col-md-7"> <h4>Confira a simualçao abaixo:</h4><br/> <table> <thead> <tr> <th>Descrição</th> <th>Valor do Crédito</th> <th>Valor da Parcela</th> <th>Valor da Meia Parcela</th> <th>Duração</th> </tr> </thead> <tbody> <?php $_SESSION['splano'] = $plano; $_SESSION['svalorcon'] = $valorcon; $_SESSION['stipo'] = $tipo ; if ($plano=='Crédito') { $tsql = " (SELECT * FROM `consulta` where tipo='$tipo' and credito>=$valorcon order by credito limit 2 ) UNION (SELECT * FROM `consulta` where tipo='$tipo' and credito<$valorcon order by credito desc limit 2 ) order by credito "; } ELSE { $tsql = " (SELECT * FROM `consulta` where tipo='$tipo' and parcela>=$valorcon order by parcela limit 2 ) UNION (SELECT * FROM `consulta` where tipo='$tipo' and parcela<$valorcon order by parcela desc limit 2 ) order by parcela "; } $_SESSION['sqlExecutar'] = $tsql ; //echo $tsql; //exit; $sql = fbd($tsql,"","Seleciona as empresa"); $num_rows = mysql_num_rows($sql); if ($num_rows>0) { ?> <script language= "JavaScript"> location.href="resultado.php" </script> <?php } ?> <script language= "JavaScript"> location.href="simulador.php" </script> <?php while($dados= mysql_fetch_array($sql)){ ?> <tr> <td align="left"><? echo $dados[descricao]; ?></td> <td>R$ <? echo valor_ponto_virgula( $dados["credito"] ); ?></td> <td>R$ <? echo valor_ponto_virgula( $dados["parcela"] ); ?></td> <td>R$ <? echo valor_ponto_virgula( $dados["parcela"]/2 ); ?></td> <td><? echo $dados["duracao"] ; ?></td> <?php } ?> </tbody> </table> </div> </div> <p> </p> <p> </p> </div> <?php } ELSE { ?> <h2>SIMULE AGORA SEU CONSÓRCIO!</h2><br/><br/> <div class="col-md-6"> <img src="img/simule.jpg" class="imagem" alt="Vitor Consórcios"> </div> <div class="col-md-1"></div> <form action="simulador.php" method="post" name="dados" id="dados" onSubmit="return validaform()"> <div class="col-md-5 esquerda"> Selecione o bem<br/> <select name="tipo" type="text" class="contat3" placeholder="Selecione o bem"> <option value="Imóvel"" style="background-color: #fff;">Imóveis</option> <option value="Automóvel"" style="background-color: #fff;">Automóveis</option> <option value="Moto" style="background-color: #fff;">Motos</option> </select><br/> Selecione o plano<br/> <select name="plano" type="text" class="contat3"> <option value="Crédito"" style="background-color: #fff;">Crédito</option> <option value="Parcela"" style="background-color: #fff;">Parcela</option> </select><br/> <input name="valorcon" type="text" id="valorcon" class="contat3" placeholder="Digite o valor" maxlength="1000" /><br/> <input name="nomecon" type="text" id="nomecon" class="contat3" placeholder="Nome" maxlength="1000" /><br/> <input name="telefone" type="text" onkeypress="Mascara('TEL',this,event);" type="text" id="telefone" class="contat3" placeholder="Telefone" /> <!--- <input name="tel2" type="text" id="tel2" onkeypress="Mascara('TEL',this,event);" /><br/> ---> <input name="emailcon" type="text" id="emailcon" class="contat3" placeholder="E-mal" maxlength="1000" /><br/> <input name="cidadecon" type="text" id="cidadecon" class="contat3" placeholder="Cidade" maxlength="1000" /> <br/><br/><br/> <a id="enviar-form" class="button solid-color" href="#">Enviar</a> <input type="submit" id="enviar-form-btn" style="display: none;" /> </div> </form> </div> <p> </p> <p> </p> </div> <?php } // 14-05-2018 ?> </div> </div>
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 |