Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I just want to build my first dynamic Website. I want to use PHP, MYSQL, AJAX, HTML, CSS
I have some beginner Questions:
Should the Header and Navigation Bar excluded in a header.php and print out with echo?
Should the design tags in the echo in php (like: <a>1 Test test</a>) or only return the the data
Is there a good example for making dynamic websites?
My main problem is that i don't know how to make a clear structure. Where to make the right design (print out in the php ?)
If it is really your first website, I'd actually recommend using nothing in terms of frameworks. This buys you some time to get comfortable with HTML/CSS, SQL and PHP, without overloading you with higher-level principles such as MVC (model/view/controller) and others. I'm mostly concerned that starting with a framework right away makes the learning curve to steep, and skips over things such as getting comfortable with the programming language you'll be using.
You'll eventually make a mess with way, but this will only make you appreciate the frameworks more; you can then make the transition to using a framework such as CodeIgniter, Symfony or CakePHP (or others, because there's a whole bunch more).
Other frameworks that I really like working with are Play! for Java, and Rails for Ruby. Since you stated you're a beginner, you might consider these as well.
Well, to answer all your questions at once.
The only technology you need is template.
Template is a typical PHP script, however, consists mostly of pure HTML, with some PHP code only to display dynamically generated data.
Create a main site template contains both header and navigation bar and footer everything else excluding actual page content.
Then create separate pages ("sections" of your site: news.php, links.php, etc.)
But make every page of 2 parts: getting data part and displaying data part.
While getting data, not a single character should be printed out.
If some errors occurred, display an error page.
Once you get all your data with no errors - it's time to include a main template.
A typical script may look like
<?
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
// setting title for using in the main template
$pagetitle = "Links to friend sites";
//etc
//set page template filename
$tpl = "links.tpl.php";
//and then finally call a template:
include "main.tpl.php";
?>
where main.tpl.php is your main site template, including common parts, like header, footer, menu etc:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>
and links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
Eventually you may come to more complex designs, like with front controller one, but for the first site this one is both easy and powerful.
Yes, I do recommend you include header and navbar scripts from another file.. where you can maintain them independently. I think that is pretty important.
I recommend you echo/print html from php, rather than insert php into html (easier when doing things like parsing $_GET/$_POST etc)
I recommend that you create a template, and another script which has functions that print (or echo) the html tags, header, footer, title bar, navbar etc. Just include the script with the functions and all your pages can have the following structure:
<?php
include 'html_display_functions.php';
/* put lines here to parse $_GET and $_POST, session_start()/$_SESSION,etc
if needed */
print_html_pre_content();
print '<p>Hello, world! or other content.</p>';
print_html_post_content();
?>
I have found this to be pretty clean, and it is easy to add functionality when you get to messing around with $_GET, $_POST and $_SESSION, etc.
I'd suggest to use some template system (Smarty would be good).
It does not really matter where do you put your header and navigation bar at first glance. When do you need to exclude Navigation bar and store it separately? When you want to have ability to include different nav. bars in different parts of your website.
For example I have a website with several subdomains: about.website.dev, special.website.dev and, let's say, terms.website.dev
At about.website.dev my navigation bar's entries will be: "Who I am", "What do I do", "How cool am I"; at special.website.dev: "Goods", "Solutions", "Tips" , etc.
Your navigation bar's template is the same: just a loop though all entries, but content differs. In this case you separate navigation bar from header. If you don't use templates, you just create three files (in this case): about.nav.php, special.nav.php and terms.nav.php and then you just include appropriate navigation bar.
If your nav. bar is all the same everywhere on your website, you can store it in header.php. Once you need to separate, it will not be difficult, but still I'd suggest to use templates though just to get used to "proper website development".
Take a look at different templating systems like Smarty or Savant. I, personally, like Django's (python) templating system most. And get used to separate your view and business logic.
IMHO, you would be better off having a look at a php-based web application framework. such as the list at http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks#PHP
Even though it may be a little more to learn upfront (the framework as well as php), they all have solid enough structures to develop dynamic websites with. Find one that is light enough and has good tutorials and you'll find yourself learning the php language along the way. I believe this will be easier than just using raw php at the beginning stage.
When you know more you can then make a judgement call on which frameworks you prefer and suit your needs or coding style or even revert back to raw php.
If you want a good book on the subject, try
MySQL/PHP Database Applications by Brad Bulger, Jay Greenspan and David Wall
What you are asking is pretty much a matter of taste. The more complex your application will be, the more work should go into an elaborate and maintainable structure.
My opinion is: Learn the basics first and then look at frameworks. It makes it a lot easier if you understand what happens under the hood.
Try Agile Toolkit, probably the easiest PHP UI framework to get started with designed for web software.
You'll step over many problems. http://agiletoolkit.org
Depending of the choice of framework/plain PHP, you should do it in accordance with their practices. For instance in Agile Toolkit you use templates, so you put your header and footer into templates/jui/shared.html file. It's explained in the first screencast.
If you reinvent the wheel and go ahead with plain PHP, then you should do better do include 'header.php'; . Good framework lets you NOT learn about inner workings of web software. Bad framework needs you to know everything anyway.
There's a lot of good answers here already - but just to add....
Do split functionality into separate include files - and use a consistent way of locating these files.
Do find a good PHP coding style and stick to it. e.g. horde, PEAR
Don't have code or HTML executed inline in include files - it should only do something when you specifically invoke it from your controlling script.
If you are including files which generate HTML, make sure they provide functionality for closing any tags they open. i.e. not just a 'header.php'
Since CSS and Javascript files should not be directly declared outside the HEAD of the HTML document do look at ways by which invoked functionality can add these into an existing HTML document - one obvious solution is to use a templating system combined with output buffering but you can also inject additional JS and CSS files into the HEAD section later in the document by using javascript.
Use MVC - http://www.yiiframework.com/doc/guide/1.1/en/basics.mvc
See Yii-framework http://yiiframework.com, it has all you need :)
For some years that I've been using my own PHP template engine, which is not really "my own" as I saw it on a tutorial many years ago. However, I've refactored most of the code making it simpler and easier to use. I rarely make a PHP project without it.
It's very basic and the class only has 3 methods, load, assign and render. The load loads the template file (usually HTML) and saves it as a string variable. The assign allows to assign references in the HTML to variables in the form of {reference}. The render parses the template file and replaces the references with the variables. That's basically it. Very basic, very simple and a time saver for me.
I like this template engine because I hate to mix PHP with HTML and whatever. And so I'm not very fond of PHP itself as template engine (like WordPress templates), although very powerful for such thing. I don't like the idea of saving my files as .php files and then include/require them with a bunch of mixed PHP code, I like to keep it simple.
However, has rudimentary as this template engine is, it doesn't allow for conditions and loops, two very important things that sometimes are needed. So far I've been working around that issue by separating template files and then do all the conditions/loops in the controller. For instance, I have the main template file which has a <ul> list where the items come from a database, I'll just have a separate template file with one line of code for the <li> item. Do the loop in the controller and render the as many <li>'s as needed.
This was an introduction so you understand where I come from. Now to the real question...
I've been thinking and experimenting alternatives to this method and start using PHP in the HTML template files with as little code as I can. For instance, like this:
<ul>
<?php foreach($array as $val): ?>
<li><?php echo $val; ?></li>
<?php endforeach; ?>
</ul>
And the in the controller something like this:
// assuming the data comes from a
$array = array('Item 1', 'Item 2', 'Item 3'); database...
ob_start();
eval(' ?>'.$TPL->render('main').'<php ');
echo ob_get_clean();
First point I want to make is that this presents a problem for me. It kinda defeats the purpose of this template engine. There I am, calling echo $val where I should have a reference to be replaced. But wouldn't it be completely idiotic to have a reference to be replaced in the template rendering when I have the $val variable right there waiting to be used? But I also don't like the idea of using lots of PHP code in my template files, I would prefer to avoid as much as I could without compromising the whole thing too much. However, I don't see how could I have a reference in the place of the echo and have it replaced by $val for each loop. What your take on this?
Secondly, I would like your opinion and [more] issues that you think this solution might have. Or if there's some thing wrong in the code or how could it be improved, etc... I know I could use an extra method to do all the output buffering and eval to simplify the template rendering, but I'm looking for other stuff I may have overlooked or completely forgot about or simply missing the knowledge, most likely.
Maybe I'm thinking too much into this, maybe I should just forget about the whole thing and keep doing this as I've been doing for the past few years. It worked very nicely for me and simplified all my projects. In the end, I'm basically looking for a way to simplify conditions and loops in my template files without requiring extra template files, some with only a couple of simple lines of code.
I believe the way other languages address this is by offering server side markup, like the asp repeater control and I found this question here too which suggests you stick with your solution and gives a -1 to person who suggests rolling their own custom template tags to achieve the same thing... maybe it just doesn't get much simpler and building it is over-design.
I learned PHP by hacking away at phpBB2, even submitting a few mods to their database, which others downloaded and used. (I don't believe phpBB2 is supported any more with phpBB3 out so long now, so the v2 mods database is no more.)
One of my favorite things about phpBB was their templates system, which let the editor completely separate the HTML and the PHP. PHP files contained PHP: logic, database queries, and activating the templates. TPL files contained templates: HTML, template variables, and specialized HTML comments to allow for conditional or repeating blocks.
However, any time I see someone's PHP code online, it's either a small snippet working with a single function or such, or the PHP is full of strings containing HTML (or worse, HTML with PHP interspersed). phpBB is the only PHP I've looked at which actually separates the language and the markup language, suggesting to me that few, if any, other PHP codebases do such a thing.
I'm looking to start working with some PHP again, but this time it won't be a phpBB forum, and it will be on a team. Based on my experience, separation of PHP and HTML is uncommon (please correct me if I'm wrong on this!). However, I'm so used to that dividing line, I hate reading mixed PHP and HTML.
In the "real world" of PHP programming, what's the preferred method:
PHP files with strings of HTML
HTML files broken up with PHP blocks
PHP and HTML completely separate (I wish?)
Something else?
If you want to separate the PHP from the HTML you can use a template engine (Like smarty http://www.smarty.net/).
Personally, I see no reason to add a template system/language into the mix, when PHP is already a prefectly good solution.
My preferred approach is to separate the display from the logic of the application. This could take the form of a full blown MVC framework. However, it could also be a simple matter of how you go about writing your code.
Expansion:
Ever since making the mistake of interspersing my HTML with copious amounts of ASP code, I have tried to separate page logic from display. Within a single page, this means placing all of the page logic at the top, storing the information to be displayed in variables and then echoing them out within the HTML at the bottom of the PHP file. The only logic which appears in the HTML portion is display logic. In other words, simple error handling, ifs, loops, etc. Basically, the same stuff that you'll find in most templating languages.
My reason for avoiding templating languages is that it's yet another form of syntax that I need to worry about. What's the point? PHP provides more than I need for this purpose.
Meanwhile, you can take a simple MVC approach by separating things:
controller.php
<?php
// some application logic
$data['message'] = 'Hello, World.';
include 'view.php';
exit;
?>
view.php:
<html>
<head>
<title>
A simple 'MVC' view
</title>
</head>
<body>
<p>
<?php
echo $data['message'];
?>
</p>
</body>
</html>
This isn't without its drawbacks and issues. However, if you think you can have complete, clean separation between application logic and display, you're mistaken.
We use a customized code igniter base for MVC and just have logic and layout separated. that doesn't necessarily mean there's no php in our html, just that its not used for logic. It's perfectly okay to loop through a recordset with php code in a template imho, just don't try to talk to business objects and actually do stuff in the layout templates. You could ofcourse also look into something like tal or a million others for the templates if you really want to get rid of all php code there. I'm kinda thinking that's mostly overkill though, unless "insert special circumstance here"
edit fixed typo
In my experience, a lot of PHP development, whether for better or worse, ends up being php files connected to each other through includes that print out snippets of HTML as needed.
Mind though, most of my PHP experience is for more of a "we just need something that works" solution than a "we need the most elegant and efficient solution"
any time I see someone's PHP code online, it's either a small snippet working with a single function or such, or the PHP is full of strings containing HTML (or worse, HTML with PHP interspersed).
Yeah, the general quality of code out there is embarrassing.
Whilst you can go to a full-blown templating engine of your own, that may be overkill and in many cases the limited domain-specific-languages they provide will get in your way, when you could just be writing presentation logic in PHP.
If you want to still be writing normal PHP, but without the spaghetti:
Keep action code at the top of the file or in a different file. Put only application logic here, not any kind of HTML or templating. Any information generated in this stage that needs to be displayed by the template needs to go in a variable to be passed to the templating part, not printed out in the middle of a load of business logic.
Take your knowledge of tag-based templating and apply it to PHP. Have a single, correctly-indented hierarchy of code for both HTML and PHP presentation logic, as if you were writing ‘well-formed’ XML (whether or not you're actually using XHTML). Avoid putting HTML in strings at all costs.
Define an easier way of calling htmlspecialchars(), because otherwise typing that all the time is going to be a real pain, and if you aren't typing it all the time you're going to have potentially security-sensitive errors.
To summarise, eg.:
<?php
// active code here
// do things
// put any errors in a $errors array
// this trivial function would presumably be in an include
//
function h($s) {
echo htmlspecialchars($s, ENT_QUOTES);
}
?>
<body>
<?php if (count($errors)!=0) { ?>
<ul id="errors">
<?php foreach ($errors as $error) { ?>
<?php h($error); ?>
<?php } ?>
</ul>
<?php } ?>
...
</body>
In the "real world" of PHP programming, what's the preferred method:
Oh, in the real world of PHP programming, the average project has a mishmash of approaches thrown together without any thought. In the real world the code is unmaintainable, bug-ridden, and insecure. You don't want to look at the Industry Standard, because the Industry Standard is to be broken in every way.
I prefer to use a template system to minimize the amount of PHP code contained in the HTML files. I really don't see any way to entirely separate PHP from HTML, but I feel that it is sufficient to separate business logic (database) from presentation logic.
My template system is home-baked, but I'm sure you can find a variety that would work by preforming a google search.
Based on my experience, separation of PHP and HTML is uncommon
True. But lot of PHP code is written by inexperienced developers. Further, PHP does not encourage, but rather discourage writing good code, and the ability to mix HTML with programming code is one of the examples of this.
If you expect to do high quality code, to be able to easily maintain and extend it, I highly recommend using template engine or something similar. Mixing both has a huge impact on the readability of your code, and will result in something becoming worse and worse over time. Refactoring will be painful, if not impossible.
Now, you have a large choice of the way to separate HTML from PHP
The most obvious one is to use an existing layout engine. There are plenty of them, some very well done and with a very low performance impact.
You can also write your own engine. It may not be a good idea on a big project (why reinvent the wheel?), but can be a solution either on a tiny project or when you need something very specific.
The last way I use in most projects is to build XML from business layer (XML serialization is quite easy in PHP), then to use XSLT to transform this to HTML page. It enables to do websites which are much easier to maintain and more easy to understand, and, by the way, enables to access the website data programmatically (loading XML instead of HTML page) when need. On the other hand, it decreases performance hugely, so is not intended for large websites with thousands of queries per second.
Most code starts with PHP and HTML strings, then evolves into a templating system during a big rewrite. Separating content from logic up front requires design, planning and communication among the team. Using XML or JSON instead of PHP arrays as the data format makes this easier.
you can mix up PHP inside HTML or vice versa simply by adding opening <?php and closing ?> PHP tags between your HTML.
<!DOCTYPE html>
<head>
<title>Hello world as text</title>
</head>
<body>
<?php
echo "<p>Hello world</p>";
?>
</body>
</html>
For more details : https://stackhowto.com/how-to-combine-html-and-php/
What is the best, easiest, and fastest way to use a template for a page. Right now I have been using a function to create my template for each page.
$title = "Kick Me";
<?php pageHtmlHeadStart($title)>
<!-- Were Javascript would go -->
<?php pageHtmlHeadEnd(); guiHeader(); ?>
Content went here.
<?php guiFooter; ?>
I uses to use includes...
<?php include('header.php'); ?>
Content went here.
<?php include('footer.php') ?>
I was thinking about using PHP Object to do the same thing too. It would run like the functions way of doing it. I would create a GUI class that would have the template wrapper and include some scripts to display content (via echo) that I use a few time over again on different page.
I probably will answer my own questions when say this... I like the current way do it with the functions. I just don't know if this is bad coding habits.
In the context of templates, there is nothing wrong to use include() statements. They make clean looking code and makes it easy to share html snippets between templates.
Whether to use instance methods, static methods or functions for "template tags" depends on the architecture of your framework or application. While generally OOP is really good thing, making everything an object doesn't magically make your code better.
PHP itself does make a good template language. There is no need to invent another "language" for templates – neither is it wrong, as long as you cache your parsed files (like Smarty does).
You may want to check out Savant and Smarty template engines. I also recommend you to study various PHP MVC frameworks and see how things are implemented there: Symfony, Kohana.
If you want a template, then use a templating language. Using PHP for templating is definitely not a good practice according to me.
I was recently brought on to help with a project that was made up of individual HTML files with the exception of a PHP contact form. So there's not even a hint of object oriented programming, MVC, or layouts (or even PHP for that matter).
The project is quite large, but I wanted to slowly integrate the Zend Framework into this project, mostly to start using layouts. There are so many redundancies that it is such a waste of time to make small updates that should have been made in one file.
In the early days of PHP, you could separate your content blocks by including them in each page (a header and footer for example). Now, using MVC frameworks like the Zend Framework, you can create layout files that include the individual page content (views) using a view helper. I really like this because it means I only have to "include" my header, or footer, in one place.
However, I'm not sure how this would work without dispatching/bootstrapping the application (i.e. using the Zend Framework MVC components as standalone components instead). What would be the best approach to switching the site over to use layouts? How would it work? Is this even a good idea?
I've recently begun a transformation of a mish-mash file structure* to make use of ZF's layout & views. The goal is to move all files containing html into the recommended file structure for layouts and views. This is how to prepare for it:
Extract all markup from each file, keep variables in it but no logic. Name this file /application/views/scripts/page/view.phtml (for example /application/views/scripts/index/login.phtml)
Create a skeleton that fits most pages as /application/layouts/scripts/layout.phtml and let it contain something like this:
<?php echo $this->doctype('XHTML1_STRICT'); ?>
<html>
<head>
<?php echo $this->headLink(); ?>
</head>
<body>
<div id="wrapper">
<?php echo $this->layout()->content; ?>
</div>
</body>
</html>
(Add Zend to your include path and register its Autoloader.) Create a file that will be included in all of your files (unless you have a single point of entry, in that case - place it there!) Create a reference to your layout, equivalent to this:
$view = new Zend_View();
$view->setScriptPath('/application/views/scripts');
$layout = new Zend_Layout();
$layout->setLayoutPath('/application/layouts/scripts');
$layout->setView($view);
Zend_Registry::getInstance()->set('layout', $layout);
Each php file you have left (with logic, not html) needs to have access to the layout, and modifying it:
$layout = Zend_Registry::getInstance()->get('layout');
$view = $layout->getView();
$view->headLink()->appendStylesheet('/css/a_css_file.css');
// most important step, done automatically when using MVC, but now you have to do it manually
$layout->content = $view->render('index/login.phtml');
echo $layout->render();
Most important next step is adding another layout:
// /application/layouts/scripts/blank.phtml
<?php echo $this->doctype('XHTML1_STRICT'); ?>
<html>
<head></head>
<body>
<?php echo $this->layout()->content; ?>
</body>
</html>
and in one of your logic-containg files
$layout = Zend_Registry::getInstance()->get('layout');
$layout->setLayout('blank');
Ideally, in a near future you can start adapting to a MVC-like structure by looking at a design pattern like Front Controller.
*One file: model, controller, html, in no logical order.
You can certainly use Zend_Layout in isolation and it's detailed in the manual:
28.2.3. Using Zend_Layout as a Standalone Component
I believe you would then need to capture you script's output via output buffering, and pass it to the layout to be echoed.
This situation is not ideal, and without moving to the full MVC I'd probably recommend using a different, basic templating system or following the advice in other comments here.
Personally, I'd recommend not using the Zend Framework if you're only planning on using it for template/layout management. There are much better solutions for templating with PHP, with Smarty being the obvious choice (formerly part of the PHP project).
Smarty does provide a reasonably easy integration with the Zend Framework, if you need to do this at a later date, and there are a few articles on it on the Zend DevZone.
I'm not sure if this is what you're looking for, but the bbc has some videos where they use parts of the zend framework without using the whole MVC. I think they are in parts 4 & 5, http://bbcwebdevelopers.blip.tv/
Zend_Layout isn't really about including a header or footer, rather it is best used to insert various bits of content into a single large template. It's pretty sophisticated and as well as common use cases such as inserting the main body of content you can insert HEAD tags such as CSS, scripts or title tags and custom placeholders such as navigation.
From your description I'd go for a simple PHP include header and footer solution. It will be easier to implement and will remove any duplication of common template elements.
If you really want to use this to learn Zend Framework you could use Zend_Layout in the standalone mode as dcaunt suggests. There is no point trying to use the MVC bootstrap system since your site doesn't appear to need it. I'd simply do something like use URL rewriting to send all *.html requests to a single PHP file which then starts Zend_Layout and loads the requested file into the $layout->content variable via something like file_get_contents()
You could then also use ZF for the form processing if you wished.
i dont think you can do this by default, i think you need to use the Zend View as well.
But i am sure you can modify the Zend_Layout to work with your existing setup. Sorry i cant be more specific on how to do this, because it depends a lot of what is currently in place.
As a starting point i recommend looking into Smarty integrations into Zend to see how you can modify it.