Best way to store widgets, XTHML snippets and containers in PHP - php

I have a a few XHTML widgets and containers that have static or mostly static content. When I say mostly static, I mean a widget which is using one or more variables passed to it from a DB or a configuration. These are all used in more than one frontend page. Currently, I have stored them as PHP functions that return a XHTML string, and these functions are stored in a singular "functions" file that is "included" on every page. Where applicable, I either pass these functions configuration values or do some DB calls from within.
Is there another better way to store these in PHP code? Or is what I am doing pretty standard?
(I am not using Smarty or another template system and I'd rather not add another layer of abstraction.)

That's pretty standard, most you can do is separate them into files for each and then have a "includes" files that includes each one of them.
This way you would only have to load what you need per script / page.

(I am not using Smarty or another template system and I'd rather not add another layer of abstraction.)
I know this isnt what you want but this is exacly what id do. I wouldnt necessarily use a template engine with its wone grammar but i would use php and make seperate snippet templates containing the structural markup and then pass in what i need for example:
function get_partial($path, $args = array())
{
ob_start();
include($path);
return ob_get_clean();
}
function include_partial($path, $args = array())
{
echo get_partial($path, $args);
}
Then in your template:
<div class="<?php echo $args['classname']?>">
<h4><?php echo $args['title'] ?></h4>
<?php echo $args['content'] ?>
</div>

Related

If I don't use a template engine with my PHP, what should my code look like?

I don't want to use an MVC framework. I don't want to use a template engine. I am a few man shop where the developers where all the hats, no graphic artists. We do it all (all layers). I do not want code mixed with presentation, like I have with Classic ASP.
But, I do not know what my code is suppose to look like between server side and the actual presentation.
If I'm not emitting HTML in my server side code, how does it get to the HTML page so I can do things like <span><?= $myvar ?></span>? and put loops in the html page?
Thank you for any advice.
For using loops and all, I use the alternative syntax for the control structures.
An example:
<div id="messages"<?php if(!(isset($messages) && count($messages))): ?> class="hidden"<?php endif; ?>>
<?php if(isset($messages)): ?>
<?php foreach($messages as $message): ?>
<div class="message"><?php echo $message; ?></div>
<?php endforeach; ?>
<?php endif; ?>
</div>
For more information, see this: http://php.net/manual/en/control-structures.alternative-syntax.php
Oh also, I use a semi-MVC structure, where I have a class that handles templates (views), basically it's just a class that I create an instance of, pass a set of variables, then render the template when the instance get destroyed. I have an array of variables in that class, and then use extract to pass all variables in the include, like so:
extract($this->variables, EXTR_SKIP);
include($this->file);
EDIT: Here is the same example in Smarty:
<div id="messages"{if isset($messages) && !count($messages)} class="hidden"{/if}>
{if isset($messages)}
{foreach from=$messages item=message}
<div class="message">{$message}</div>
{/foreach}
{/if}
</div>
Simple PHP projects usually generate the full HTML in-place instead of populating templates, so you'd just echo it out in your PHP code.
This gets messy, so you WILL end up coding some kind of templating system for any moderately complex website.
A possible alternative is to serve your page as completely static HTML/CSS and use AJAX to fetch the actual contents dynamically (JSON would be a good transport format, it's native to JS and can easily be generated from PHP). This gets you rid of all the HTML littered across your PHP code. Whether this is a viable alternative or not depends on the case.
<span><?= $myvar ?></span> works.
A loop would look like:
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
</body>
</html>
Example taken from here.
I really recommend that you use the php Template Inheritance system. (Don't let it scare you, it's only one file.) This is a simple set of functions that helps you to build extensible PHP views without the problems and limitations of manual includes.
It's still Pure PHP, so you don't need to learn some strange template language. It may not look like much, but it's really powerful once you start using it.
To be sure, you can do it all by yourself - but what you want is still MVC pattern, or separation of concerns ("I do not want code mixed with presentation"). Or at least MV, for very simple applications (although it's still dirty, having models directly influence the view).
The easiest way to achieve this is to first collect and process all data, then just print them. No complex code allowed in the php files directly exposed to the web.
<?php
require('model.inc');
process_capuchin_monkey_order_form();
?>
...
<h1>Thank you for your order of <?php echo $order->num_monkeys; ?> monkeys.</h1>
...
typically you would want to just make sure you have as little PHP in your HTML as possible. This means doing all of the data processing before hand, and simply passing a set of variables in one way or another to a method or function that includes the HTML.
Any HTML with PHP intermixed could be considered a template. Here's a simplified example:
// view class
class View {
public function render($html_template) {
include('view_path/' . $html_template . '.php');
}
}
// html template file 'view_path/main.php'
<html>
<body>
<h1><?= $this->title ?></h1>
</body>
</html>
// usage
$view = new View();
$view->title = 'Some Title';
$view->render('main');
You should use an MVC-like separation of concerns no matter what you do. This means:
At least one file is all html and is given a handful of variables. (view/template)
At least one file is all php and only talks to the database. (model)
At least one file processes the http request, pulls data from database, and executes the view.
The core of every php templating language is the use of extract() and include inside a function:
function render_template($___filename, $___data) {
extract($___data, EXTR_SKIP);
include $__filename;
}
You can pretty this up with a class interface (view objects) or with output buffering, but this is the core of every template system. Your controller's responsibility is simply to assemble that $__data argument (usually with data from a database) for a given view.

What's the best way (to avoid modifying repeated code) to build multilingual web pages

What's the best way (to avoid modifying repeated code) to building multilingual web pages?
I know how to build a multilingual web page without having to modify CSS and Javascript files.
But I can't think of a neat solution for HTML and Php files. Because if I have HTML or Php files for each language, I would have to modify each one if, for instance, I add an extra div or other element.
I was thinking to have something like this:
<div id="multilingual div">
<p><?php echo($multilingual-paragraph); ?></p>
</div>
(So, even if I modify these elements, I will just do it once, because the text that is in other language will show up from the variable).
I don't know Php, so I don't know how to tell Php to display a different variable according to the language (I think it has something to do with IF conditions)
Is this a good way of creating multilingual web pages or there are other methods?
(So with this
Check out the gettext() function. You don't really need to build different files for different languages. Altough, you'll have to struggle with the translation files.
You can implement a constants-solution for output messages. Using APC's cache functions, you can store multiple messages inside the cache and load them according to the pages you're viewing (this might not be an easy solution though, you need to know php for this).
This would allow you to maintain an array with values for each language in the cache. For example:
apc_constants_define('en',array('welcomeMessage'=>'Welcome!'));
apc_constants_define('es',array('welcomeMessage'=>'Bienvenidos!'));
apc_constants_define('de',array('welcomeMessage'=>'Willkommen!'));
through AJAX/select form, you can allow the user to choose the language they want to view your pages.
This language would be stored inside a session:
$_SESSION['language'] = 'en';
Next, on every page's top, you should check the session (simple switch statment) and load the constants from the cache accordingly.
apc_load_constants($_SESSION['language']);
then your html page would look like this:
<h1><?php echo welcomeMessage; ?></h1>
This is, as I see it, the most efficient way of internationalizing your website, and with an easily maintainable system, that doesn't require you to delve into the code when you want to translate your page to Romanian.
As you said, you have php and html language files, one way is to go like this:
$lang = '';
switch ($lang_file)
{
case 'en.php': $lang = 'whatever'; break;
case 'fr.php': $lang = 'whatever'; break;
// etc
}
<div id="multilingual div">
<p><?php echo $lang; ?></p>
// or you may include files
<p><?php include_once ($lang); ?></p>
</div>

Whats the best way to output data from a database using php?

I'm relatively new to php, and I'm working on a project using a mysql database. The project consists of users being able to write posts, which are then shown in a list format. The problem is, the posts are shown in different locations on the site, like the index (main) page, and the users profile page. Similar to twitter if you're confused. My question is, what is the best way to display the posts? Currently I'm using a class that I created. It has functions to retrieve posts from the database, save them all in a multidimensional array. Then another function in the class formats the entire list using foreach, and then returns the formatted HTML list of posts. All I have to do is echo what is returned. But I read somewhere that it's bad practice to write functions (especially class functions) that output HTML. What would be the best way to do this, without having to rewrite the same code on every page the posts are shown. Is it really bad practice to use HTML in functions?
Example...
a profile page looks something like this.
<
require('class.php');
require('header.php');
$profile = new Profile();
$userProfile = $profile->GetUserProfile($userID);
echo $userProfile;
$class = new Posts();
$posts = $class->GetUserPosts($userID);
echo $posts;
require('footer.php');
?>
And the main page looks something like this
<
$class = new Posts();
$posts = $class->GetAllPosts();
echo $posts;
?>
where the profile class would take a user id and output the users profile, already formatted in HTML.
And the posts class has functions to return a determined number of posts already formatted in an HTML list.
Should I keep everything in the class, or is there a better way?
Thanks
Well, if you're not using an MVC framework of some kind, then I would say that having functions that output HTML isn't going to kill anyone.
Generally however, it's helpful to separate HTML from logic, and this is usually done by creating an HTML template and template fragments with interspersed PHP. Something like this:
<div>
<h1><?php echo $title; ?></h1>
</div>
You could then set up a $title variable (and others), and include('title_fragment.php') to output that bit of HTML. You can extend this to work with entire pages, making it so that your code only has to deal with small amounts of data that get passed to the template.
When it comes time to make changes to the page layout or look, you don't have to go hunting through the code to find the bits of generated HTML... you can go straight to the template files.
This is important for maintainable design as well as code, and it makes it easier to produce other output types later on.
With PHP, one of the simplest libraries for separating the two is Smarty templates. Using Smarty (or any other templating library), you can write an HTML file with the layout and some simple loops or other constructs, and then render that template using a data structure. At the very least, I would suggest altering your class to utilize a template and produce output that way, rather than a mish-mash of print or echo statements with a bunch of HTML in them.
I'd even shy away from #zombat's solution of echo statements in HTML fragments, they quickly become ugly.
Example Smarty template to achieve something like what you want:
{section name=i loop=$posts}
<li>{$posts[i].author} — {$post[i].text}</li>
{/section}
And some PHP supporting code:
// Instantiate Smarty object
$smarty = new Smarty();
// Assign a hash of data
$smarty->assign('posts', array(
array('author' => 'Jim', 'text' => 'Hi this is my post!'),
array('author' => 'Sally', 'text' => 'My first post to the system')
)
);
// Use the file with the above template in it
$smarty->display('posts.html');
The part where you assign data to the template should probably be done via some programmatic means to convert your list of class objects into a list of hashes.
This way you can easily change the way the output looks just by editing the HTML template and you don't have to worry about touching any code to change the output.
Your class should ideally provide the data only. Use another PHP file or generic class to output HTML, so later you could output e.g. XML, JSON, etc from the same data class. This separates your data processing (model/controller) from your data representation (view).
I would disagree with using a template engine like Smarty. PHP is a template engine.
You can use output buffering. It's helping to build your templates and not be forced to process data in the display order.
<?php
$posts = take_data_from_class();
ob_start();
require_once('path/to/posts.php');
$html_posts = ob_get_clean();
// you can do the same with other parts like header or footer
ob_start();
require_once('path/to/header.php');
$header = ob_get_clean();
ob_start();
require_once('path/to/footer.php');
$footer = ob_get_clean();
?>
In posts.php you can display the posts:
<? foreach ($posts as $p) { ?>
<div class="...">
post data here
</div>
<? } ?>
Now, to display the whole thing:
<?php echo $header . $html_posts . $footer; ?>
More at http://us3.php.net/manual/en/book.outcontrol.php
Enjoy!
Im not familiar with Smarty at all...how exactly does that work, and what are the benefits of using a smarty vs. just creating functions to take large amounts of data and return html containing that data just to be echoed later?

How is duplicate HTML represented in your codebase, in a non-duplicate way?

Most HTML in a large website is duplicated across pages (the header, footer, navigation menus, etc.). How do you design your code so that all this duplicate HTML is not actually duplicated in your code? For example, if I want to change my navigation links from a <ul> to a <ol>, I'd like to make that change in just one file.
Here's how I've seen one particular codebase handle this problem. The code for every page looks like this:
print_top_html();
/* all the code/HTML for this particular page */
print_bottom_html();
But I feel uncomfortable with this approach (partially because opening tags aren't in the same file as their closing tags).
Is there a better way?
I mostly work with PHP sites, but I'd be interested in hearing solutions for other languages (I'm not sure if this question is language-agnostic).
I'm not a php programmer, but I know we can use a templating system called Smarty that it works with templates(views), something like asp.net mvc does with Razor.
look here http://www.smarty.net/
One solution at least in the case of PHP (and other programming languages) is templates. Instead of having two functions like you have above it would instead be a mix of HTML and PHP like this.
<html>
<head>
<title><?php print $page_title ?></title>
<?php print $styles ?>
<?php print $scripts ?>
</head>
<body>
<div id="nav">
<?php print $nav ?>
</div>
<div id="content">
<?php print $content ?>
</div>
</body>
</html>
Each variable within this template would contain HTML that was produced by another template, HTML produced by a function, or also content from a database. There are a number of PHP template engines which operate in more or less this manner.
You create a template for HTML that you would generally use over and over again. Then to use it would be something like this.
<?php
$vars['nav'] = _generate_nav();
$vars['content'] = "This is the page content."
extract($vars); // Extracts variables from an array, see php.net docs
include 'page_template.php'; // Or whatever you want to name your template
It's a pretty flexible way of doing things and one which a lot of frameworks and content management systems use.
Here's a really, really simplified version of a common method.
layout.php
<html>
<body>
<?php echo $content; ?>
</body>
</html>
Then
whatever_page.php
<?php
$content = "Hello World";
include( 'layout.php' );
Sounds like you need to use include() or require()
<?php
include("header.inc.php");
output html code for page
include("footer.inc.php");
?>
The header and footer files can hold all the common HTML for the site.
You asked for how other languages handle this, and I didn't see anything other than PHP, so I encourage you to check out Rails. Rails convention is elegant, and reflects #codeincarnate 's version in PHP.
In the MVC framework, the current view is rendered inside of a controller-specific layout file that encapsulates the current method's corresponding view. It uses a "yield" method to identify a section where view content should be inserted. A common layout file looks like this:
<html>
<head>
<% #stylesheet and js includes %>
<body>
<div id="header">Header content, menus, etc…</div>
<%= yield %>
<div id="footer">Footer content</div>
</body>
</html>
This enables the application to have a different look and feel or different navigation based on the controller. In practice, I haven't used different layout files for each controller, but instead rely on the default layout, which is named "application".
However, let's say you had a company website, with separate controllers for "information", "blog", and "admin". You could then change the navigation for each in a clean and unobtrusive manner by handling the different layout views in their respective layout files that correspond to their controllers.
You can always set a custom layout in the controller method by stating:
render :layout => 'custom_layout'
There are also great helper methods built into Rails so you don't have to rely on $global variables in PHP to ensure your CSS and Javascript paths are correct depending on your development environment (dev, staging, prod…). The most common are:
#looks in public/stylesheets and assumes it's a css file
stylesheet_link_tag "filename_without_extension"
#looks in public/javascripts and assumes it's a js file
javascript_include_tag "jquery"
Of course, each of these sections could be expounded upon in much greater detail and this is just brushing the surface. Check out the following for more detail:
http://guides.rubyonrails.org/layouts_and_rendering.html
What you suggested works OK. As long as print_top_html and print_bottom_html stay in sync (and you can use automated tests to check this), then you never need to worry about them again, leaving you to focus on the real content of the site -- the stuff in the middle.
Alternatively, you can combine print_top_html and print_bottom_html into a single call, and send it HTML code (or a callback) to place in the middle.
I use the partials system of Zend_View (very similar to Rails). A partial is essentially a small HTML template that has its own variable scope. It can be called from inside views like:
<?php echo $this->partial('my_partial.phtml', array( 'var1' => $myvar ));
The variables that get passed into the construct get bound to local variables inside the partial itself. Very handy for re-use.
You can also render a partial from inside normal code, if you're writing a helper object where you have more complex logic than you'd normally feel comfortable putting in a view.
public function helperFunction()
{
// complex logic here
$html = $this->getView()->partial('my_partial.phtml', array('var1' => $myvar ));
return $html;
}
Then in your view
<?php echo $this->myHelper()->helperFunction(); ?>

Zend organization question

So I had a question on general organization of code for the Zend framework with regard to the layout.
My layout is basically this:
(LAYOUT.PHTML)
<div id='header'>
<?= $this->Layout()->header ?>
</div>
<div id='main'>
<?= $this->Layout()->main ?>
</div>
<div id='footer'>
<?= $this->Layout()->footer ?>
</div>
and so on and so forth. Now, in order to keep my code in my header separate from the code of my main and the code of my footer, I've created a folder for my view that holds header.phtml, main.phtml, footer.phtml. I then use this code to assign the content of header.phtml into $this->layout()->header:
(INDEX.PHTML)
$this->Layout()->header = file_get_contents('index/header.phtml');
$this->Layout()->main = file_get_contents('index/main.phtml');
$this->Layout()->footer = file_get_contents('index/footer.phtml');
That was working great, but I've hit a point where I don't want main to be static HTML anymore. I would like to be able to insert some values with PHP. So in my Controller in indexAction, I want to be able to load from my database and put values into index/main.phtml. Is there a way to do this without restructuring my site?
If not is there a way to do it so that I can have:
The ability to put code into different sections of my layout, such as Layout()->header, Layout->footer.
Separate these pieces into different files, so that they're easy to find and organize, like my index/footer.phtml, index/main.phtml etc.
Not have to put that code into quotes unnecessarily to turn it into a string to pass it to Layout()->header etc.
Thank you guys so much for your help.
-Ethan
Here is an idea:
Assign layout()->header the filename instead of the contents.
Put your code in this file
In your layout file, include() or require() the layout->header().
Since your layout headers/footers are now parsed, you can use them just like a view.
The ->header in $this->layout()->header is response segment. You can render parts of response using $this->_helper->viewRenderer->setResponseSegment('header'); in an action.
If you use
$this->layout()->header = $this->render('index/header.phtml');
It will even use the view, therefore keeping all your variables defined when rendering the header.
I would suggest using something like
<?php echo ($header = $this->layout()->header)?
$header : $this->render('headerDefault.phtml'); ?>
in your layout file - it will render a default header from the layout folder if the view script doesn't override it.
Have you tried looking at view helpers. They are a way of structuring view logic into reusable and modular code. In this case you would use a view helper to generate each of your required segments. So your example view script would look like
$this->Layout()->header = $this->header();
$this->Layout()->main = $this->main();
$this->Layout()->footer = $this->footer();
The benefit of using view helpers over include and require statements is that all of the file handling and name resolution is handled by the framework. The manual has more information on how to set up the paths and usage examples etc.
helpers are good. Another option is like the above, putting filenames in header/footer - put the template names and use $this->render($this->layout()->header)), etc etc. This is just like the include/require above, but more consistent.

Categories