Most effient way to template a multi lingual site - php

I am building a English/french website and was wondering if there is a best practice for such a job.
Duplicating the site and making a french and english folder with the appropriate site inside.
Using PHP to swap the content with html tags.
eg. if($lang=='en'):
Use php to swap only the content leaving the html tags the same for both. eg. if statements all over the place. Would this be bad for efficiency?
Any other suggestions would be appreciated

We have a framework in place for when (if) our site goes international that works like this...
Folder structure;
/
lang/
english/
images/
text/
dutch/
images/
text/
Any text or images that are language specific are removed from the page directly and replaced by constants. eg On the login screen, we drop in;
echo TEXT_LOGIN_WELCOME;
which is defined in /lang/english/text/login.php as;
define('TEXT_LOGIN_WELCOME', 'Welcome, please login:');
but in /lang/dutch/text/login.php it's defined as;
define('TEXT_LOGIN_WELCOME', 'Welcome, please login (in dutch):');
;-)
Each language define file is named exactly the same as the page it is used for, so when we load a public-facing page, we only need to figure out which language the user speaks and we can include the relevant language define file.
The good thing about this system is that all the language info is centralised. When you need to add a new language, simply copy the main (english?) folder, rename it, zip the whole thing up and send it to a translation service to work their magic. Of course, the downside of this system is the maintenance as both languages and content grow... If anyone has any bright ideas with regard to this then I'd love to hear them!
Btw, if you end up needing to guess a user's location by IP, you might want to check out geoIP.

Use a templating system. Smarty Template Engine is probably one of the most well-known PHP ones. Not only does a templating system serve the exact purpose you're trying to accomplish, it also makes maintaining pages far easier by separating the display code from the content (which also allows you to use the same template for lots of different content pages of a similar nature).

As the simplest way I recommend you to use i18n internationalization method & gettext catalogs (.po files).
The famous WordPress project is using it as well.

1 - Duplicating the entire site will force you to repeat every code touch-up into the 2 folders :-[
2 - If you mean somenting like
<?php if($lang=='en') { ?>
<p>English text</p>
<? } else { ?>
<p>Text français</p>
<? } ?>
This solution is perfect to manage two languages in the same page.
But you still have duplicated tags.
3 - Change only content it's really satisfaction.
Maybe proliferate of if statements can weigh down php compiling... I don't know.
Anyway document can be more concise with this approach:
<?php
function interpreter($buffer) {
$pieces = explode('#', $buffer);
if (isset($_GET['lang'])) $begin=$_GET['lang'];
else $begin = 1; // 1 to display français, 2 to display english
$tot = count($pieces);
for ($i=$begin; $i<$tot; $i+=3) { // remove one language
unset($pieces[$i]); }
foreach ($pieces as $value) { // recompose the text
$output .= $value; }
return $output;
}
ob_start("interpreter");
?>
#Français#English#
<p>#English text#Texte français#.</p>
<?php ob_end_flush() ?>
The text between ob_start and ob_end_flush is parsed AFTER php compiling.
That means are affected strings coming eg. from echo statement, not inside < ?php ?> tags.
Also content coming from php include IS affected.
But NOT external css or javascript.
Keep attention delimiter # isn't a caracter yet used elsewhere.
Maybe you'll prefer to replace with || or ^^
Of course in the future you can adapt this solution into 3 languages or more. But if you have to insert the "Third language translation#" in many lines of a big site, maybe the solution from MatW fits you.

Related

Separating php from html

I am building a website using php. I would want to separate the php from the html. Smarty engine, I guess does that, but right now its too complicated for me. Looking for a quick fix and easy to learn solution, one which is an accepted standard as well. Anyone helping please.
Consider frameworks or choose a template engine
Use a framework. Depending on your project, either a micro framework like Slim or something more complete like Laravel.
What I sometimes do when writing complex systems with quite much php code is separating it the following way (don't know your exact project, but it might work for you):
You create a php file with all the functions and variables you need. Then, you load every wepgage through the index.php file using .htaccess (so that a user actually always loads the index.php with a query string). Now, you can load the html page using file_get_contents (or similar) into a variable (I call this $body now); this variable can be modified using preg_replace.
An example: In the html file, you write {title} instead of <title>Sometext</title>
The replacement replaces {title} with the code you actually need:
$body = str_replace('{title}', $title, $body);
When all replacements are done, simply echo $body...
Just declare a lot of variables and use them in the template:
In your application:
function renderUserInformation($user)
{
$userName = $user->userName;
$userFullName = $user->fullName;
$userAge = $user->age;
include 'user.tpl.php';
}
In user.tpl.php:
User name: <?=$username?><br>
Full name: <?=userFullName?><br>
Age: <?=$userAge?>
By putting it in a function, you can limit the scope of the variables, so you won't pollute your global scope and/or accidentally overwrite existing variables.
This way, you can just 'prepare' the information needed to display and in a separate php file, all you need to do is output those variables.
Of course, if you must, you can still add more complex PHP code to the template, but try to do it as little as possible.
In the future, you might move this 'render' function to a separate class. In a way, this class is a view (a User View, in this case), and it is one step in creating a MVC structure. (But don't worry about that for now.)
Looking for a quick fix and easy to learn solution
METHOD 1 (the laziest; yet you preserve highlighting on editors like notepad++)
<?php
// my php
echo "foo";
$a = 4;
// now close the php tag -temporary-
// to render some html in the laziest of ways
?>
<!-- my html -->
<div></div>
<?php
// continue my php code
METHOD 2 (more organized; use template files, after you passed some values on it)
<?php
// my php
$var1 = "foo";
$title = "bar";
$v = array("var1"=>"foo","title"=>"bar"); // preferrable
include("template.php");
?>
template.php
<?php
// $var1, $var2 are known, also the array.
?>
<div>
<span> <?php echo $v["title"]; ?> </span>
</div>
Personally, i prefer method 2 and im using it in my own CMS which uses lots and lots of templates and arrays of data.
Another solution is of course advanced template engines like Smarty, PHPTemplate and the likes. You need a lot of time to learn them though and personally i dont like their approach (new language style)
function renderUserInformation($user)
{
$userName = $user->userName;
$userFullName = $user->fullName;
$userAge = $user->age;
include 'user.tpl.php';
}

How to change header and footer dynamically?

Good morning,
I'm creating my own framework to use in my PHP projects, and I was thinking of some way that I could add .CSS files in the header part of the page, and .JS files and scripts in the footer (keeping HTML clean and valid), but - all this dynamically.
I mean, for example, imagine I have the following structure:
index.php
components
component1
component1.php
component1.js
component1.css
I would like to include each file I need dynamically in index.php for example, keeping the code clean.
And for example, imagine that I insert JS directly in component1.php, is it possible to dynamically add it to component1.js (without human job, to save time in future)
Thanks.
One possible way of doing it would be to represent your entire template/view/whatever-you-want-to-call-it as an object:
class View {
// ...
}
The index.php file could determine which component(s) to use, create them, and then poll them for any required CSS/JS files:
$view = new View();
foreach ($components as $component) {
$cmp = new $component();
$view->addCss($cmp->getCss());
$view->addJs($cmp->getJs());
}
Once everything has been included and such, then index.php can just render the entire thing:
$view->render();
Obviously this is just an example, and your syntax will vary, but hopefully you get the idea.
Edit: You could also make the logic a little more brief by simply adding components to the view directly, and have the view's internal logic handle polling/adding the CSS/JS, rather than index.php. Of course, it really depends on what a "component" is supposed to be in your framework, so I'll leave that up to you to decide.
A very simple example of how to include your js and css assets at the top, before you start outputting anything:
// somewhere in the beginning, before html output
$js = array();
$css = array();
$css[] = 'all_pages.css';
$js[] = 'all_pages.js';
if (some_condition_based_on_page)
{
$css[] = 'some_page_specific.css';
$js[] = 'some_page_specific.js';
}
...
// in your view where you build the head section
foreach ($css as $item)
{
echo "<link rel='stylesheet' href='{$item}' type='text/css'>";
}
...
// in your view where you build the footer
foreach ($js as $item)
{
echo "<link src='{$item}' type='text/javascript'>";
}
The simplest and more portable way would be to include all files matching a certain pattern, e.g., /components/component1/header.css
This would present two complications. One is performance (you need to check all the directories of all your components). The other is isolation of components, i.e., what happens if you need a given CSS to be included before or after another which might or might not be there?
You might try to solve both problems by including a "manifest" in each component, which could specify, at first, the location of any files and where they should be included. Then your processing is reduced to examining the "components" directory and decoding all manifests, and "compiling" this in a series of directive vectors (e.g. $CSSToBeIncludedInThisOrder[] ). You might also serialize the compiled object to a cached file. Of course, any alterations to components should include removal of the compiled meta-manifest.
Later on, you might include in the manifest instruction such as conditional priorities.
All this should be done BEFORE anything is sent to the client's browser (what if component ZZZ wishes to alter the ob_ state, or maybe the encoding, or is a download override component and wants to send a Content-Type of application/octet-stream?), but the "compilation" should allow to keep perceptual latency low.
So let me clarify:
1. index.php checks whether a metamanifest.cache file exists.
2. If it does, it runs something like
$__META = unserialize(file_get_contents($METACACHE));
and goes on to #4.
3. If it does not, opendirs/readdirs the components directory,
looks what files are there, decides (but does not do yet) what to do with them,
placing those decisions in $__META, e.g. $__META['HeaderJS'][].
4. Now HTML generation begins: the __META array is walked and everything that
needs doing gets done (headers, inclusion of JS in heads, etc.).
Phase #3 might even perform some duplicate checks or versioning, say you have two components that both need "jQuery.js" to be included; instead of blindly appending "/components/comp1/js/jQuery.js" and "/components/comp2/js/jQuery.js" to a __Meta['HeaderJS'], the system could declare a conflict or decide it is solved by including only one of them, thereby further reducing processing time.

PHP - phrases/word translations in a file, best way to do it.. array, variables?

I am developing a multi-langual website. Language variables (phrases/word translations) will be entered in a specific file (one different file for each language)
I wanted to know the best way to enter the phrases/word translations, should I use a normal array?
e.g
Filename = English.php
<?php
$translations = array();
$translations['phrase1'] = "this";
$translations['phrase2'] = "that";
..
?>
and in the template file
<?php
include("English.php");
echo $translations['phrase1'];
etc...
I am pretty new to PHP so I am just looking for the best way to do it.
Any suggestions?
Thank you for your help!
There are multiple of ways to do this, the two things that pop-off my head right now are:
1) Have a look at gettext & GNU gettext page. An example implementation of this to look at is Aur Website of ArchLinux. They their app support multiple languages & its all dynamic. user can can switch between languages easily. The source code is available here, study it & see how they did it.
2) Other option could be use a framework like cakephp, as most of these frameworks have translations support
Hope it somewhat helps

Internationalization for navigation with Codeigniter

I'm trying to find the best way of structuring a multi-language site navigation,.
I'm aware of the language class in CI but it seems to be more for defining random words and lines of text that are used commonly throughout the site. It appears that creating lang files for each language and then defining translations of all the links seems like the standard approach?
In past on non-codeigniter projects I’ve setup one class like this
class Link{
var $name = array();
var $url;
var $links = array();
function add_link($links){
$this->links[] = $links;
}
}
$all_sections = array();
$section = new Link();
$section->name['en'] = "Home";
$section->name['fr']] = "Uberdurky";
$section->url = "/";
$sub_section = new Link();
$sub_section->name['en'] = "About Acme Ltd";
$sub_section->name['fr'] = "Fabuka Acme Ltd";
$sub_section->url = "/about/";
$section->add_link($sub_section);
Then I have a function to loop through and output the nav, which just looks at the current name[Lang] as defined by session or URL
This to me seems simpler and less overhead - with the benefit that both the nav structure and translations are defined in one place. But I’m new to CI so I might be misunderstanding the standard approach… ? I've googled quite a bit and haven't seen a solution here in detail.
The important thing is that it works for you. There are a lot of benefits to using separate language files:
Clean separation
Only load what you need
Easy to keep track of which languages are available
Ability to let others easily translate the files
I don't see anything wrong with the way you're doing it, but if you want to optimize - don't bother defining all the different language lines. You don't need the French version defined if the language is English. Use only the ones you need, you shouldn't have to pass the whole array to add_link(), the Link class should be detecting the language and loading the appropriate array only...
...it's starting to sound like a language file might be a good idea actually.
For now you just have French and English. I'm assuming you know both languages and (Uberdurky?) are the only one working on this aspect, so it's easier for you to define them "inline". What happens when you want to support 3, 4, or 10 languages? Things will quickly become disorganized and cluttered.
However, you don't have to use the Codeigniter Language class, you might be better off using your own system for something like navigation, which tends to be littered with 1 or two word translations, and changes somewhat frequently (either per site or between sites).
Once again, it's your call. Do what works best for you now and optimize later.
This might be helpful to anyone coming across this question.
https://github.com/cflynn07/CodeIgniterInternationalizationUtility
It's a script to take a cleanly structed HTML table of language translations, and convert them into the required language files used in codeigniter.

PHP Template Engine

I have been looking online for a tutorial to build a template engine. I know there are many engines that exist, like smarty, twig, and pattemplate, that could do exactly what I want, but I am looking to learn how to build one. I started with a template engine that added strings to an array and then displayed the array. Since then I built one using eval() (see below).
<// Define links & folders
define("ROOT_HTTP", "http://" . $_SERVER['HTTP_HOST'] . "/preprocessor");
define("TEMPLATE", "/template");
// Get the template file
$template = file_get_contents("template/template.php");
// Replace
$template = str_replace("<x Title x>", displayTitle(), $template);
$template = str_replace("<x Menu x>", displayMenu(), $template);
$template = str_replace("<x Content x>", displayContent(), $template);
$result = #eval("?>" . $template . "<?");
function displayMenu(){
return "Link1<br />" .
"Link2<br />" .
"Link3<br />";
}
function displayTitle(){
return "Site Title <?php echo date(\"m-d-y\", time()); ?>";
}
function displayContent(){
return file_get_contents("content.php");
}
It works fairly well but its not what I am looking to achieve. I would like to build something that is like the Joomla template with tags like <jdoc:include type="component" />. I would also like it to be able to handle errors inline meaning that it will display the line number of an error or when I call echo "text" it displays text in the correct position inside the template.
How do I create something along those lines?
http://www.phptal.org/ sounds very similar and has good code organization. if extension of mentioned system does not suit the needs, it would at least work as good tutorial
First of all: Immediately forget the idea about using a TE with XML-like tags. Really, it may look nice on the first glance but only causes too much work in the end and is really limiting.
Secondly I obviously recommend you to use Twig. It is clean, fast, extensible and offers all the features you need.
And lastly: I have written a small tutorial how to write a simple but powerful TE in another Stackoverflow question. It is really simple but for smaller projects it may suffice.
I cannot agree with NikiC's point of view.
XML is, although an old syntax, very powerful and brings a lot of advantages -- one of which is its similitude with properly written HTML.
There is nothing limiting in using an XML-based template syntax.
Besides, although Twig is, indeed, an excellent and famous project, it still lacks from a really good separation paradigm. It is still too dangerous and too easy to make mistakes from within the template and cause damages to the application as a whole.
Finally, the best template engine -- just as the best MVC framework -- is the one you feel really comfortable with.
I recommend having a look at FigDice]1, which was inspired by PHPTal, but takes things a few steps further, with an exclusive approach by giving the Web Designer (integrator, html-ist, etc.) a central position with the project -- much more flexible than the Twig-like approach.
I would be happy to read some feedback.
Thanks

Categories