opinion on my method for a multi language site - php

i'm working on my own way of handling a bilingual site. my method should allow proper search engine indexing and will keep everything on one page without external files.
one function would handle which content to display:
<?
function l($en, $fr){
echo ($_GET['lang'] === 'fr') ? $fr : $en ;
}
?>
then the appropriate text will display according to language in URL (/?lang=en)
<h1><? l('welcome!', 'bienvenue!') ?></h1>
for an image this is my solution:
<img src="<? l('hi-en.png', 'hi-fr.png')?>" width="100" height="20">
can anyone name drawbacks to this method if used? is it unusual to have a single function handle language for pages which would include all language content?

The general idea of using a singleton or global function like your l function is very common. You're definitely on the right track!
Your method does have some drawbacks, though:
If you have the same text or image that appears in numerous places in the code, you need to maintain the translation in every place.
Updating or correcting a translation requires wading through code, which is very difficult for inexperienced coders or non-coders (say, if you have a translator helping you).
If you were ever to add a new language, you would have to modify every source file, which would be excruciating. This may be unlikely, but if it ever happened, you'd be rather cross with yourself.
A more typical solution is to have the translations located in a separate file, either as a simple hash or as a structured data format like XML, and then your l function would just look like l('welcome'); the parameter is a key, and l will look up the correct translation in the given language from the separate file.

Related

PHP automatic footnote and endnote generator

This is more of a general information question involving endnotes than a "check my code" one. That's because I can find almost no (useful) information on the subject and don't have the skills to create this myself. But I still think it's useful to create a general brainstorm session / forum thread on the net about this.
The issue: I've written about 60 articles, a dozen of them book-length or near book-length on a site that has been manually designed with HTML5, CSS3, jquery and PHP - the latter two mainly with pre-existing code. I'm very happy with it except for one thing: endnotes! It takes forever to update them.
An average article has 120 endnotes (up to 550). It happens frequently, especially during the writing/proofreading process, that I need to add more information or want an additional endnote. That means anywhere from 2 to 30 minutes of copy-pasting "[113]s", "[114]s" around. It's hopelessly inefficient.
Ordinarily I dislike the uninspirational Wiki CMS platforms, but they have one huge benefit: cite.php plugins. Like this one:
https://www.mediawiki.org/wiki/Special:ExtensionDistributor?extdist_name=Cite&extdist_version=REL1_26&extdist_submit=
Once you have this, you just put an URL between <ref> </ref> and an endnotes gets automatically generated below a {{reflist}} tag. It's explained here:
https://en.wikipedia.org/wiki/Help:Footnotes
Footnotes are created using the Cite.php software extension. This
extension adds the HTML-like elements <ref>...</ref>, <references />
and <references>...</references>. The elements are also used in a
number of templates; for example, it is becoming more common to use
{{reflist}} rather than <references /> as it can style the reference
list.
I've checked out the plugin and it, of course, is much more than just a few lines of PHP.
My main question is if anyone is aware if this type of code has been created for custom designed websites. Or if someone has an idea how to program this manually? If it's not too hard, I might try it myself in the near future or hire a programmer.
P.S. I did study HTML5 solutions for endnotes in the past. Can't remember the details, but they were terrible. It's crucial to have one type of tag, with each one generating a new automatic endnote.
{{ }} is not standard HTML tags, but usually in some modern MVC frameworks they are used as replacement for PHP syntax like echo $foodNote which is the same as {{ $foodNote }}.
A MVC framework like Laravel use it as part of blade template.
But in the provided link you have in your question, the {{reflist}} is just referring to the content inside the tags like <ref>Content of the reference</ref>.
The provided Cite.php helper file is parsing the content inside tags like <ref>...</ref> to variable reflist inside a curly braces with the same content.
It should be not very difficult to program such thing.
Here is a simple PHP script to handle footnotes automatically. The only significant caveat is that your web page file name must end in .php or .phtml (not all web servers support .phtml). This is no problem because the web server will treat the file exactly as a .html file, except it watches for PHP tags so it can process the embedded PHP scripts.
Here is the script.
<?php
function footnote($footnote){
global $Footnotes, $FootnoteCount;
$FootnoteCount++;
$Footnotes[$FootnoteCount] = "$footnote";
print "<sup>$FootnoteCount</sup>";
}
function PrintFootnotes(){
  global $Footnotes, $FootnoteCount;
for($i = 1;$i < $FootnoteCount + 1;$i++){
  print "<sup>$i</sup>$Footnotes[$i]<br />";
  }
}
?>
You can put the script at the top of each page.
Better yet, save the script in a file named FootnoteFunctions.php. Of course, you can name it what you want or put it in a file with other functions. Just change the following include as appropriate. Next, put the following in the head of your HTML document:
<?php include("FootnoteFunctions.php"); ?>
Put this where you want the footnotes to appear at the bottom of the page:
<?php PrintFootnotes(); ?>
To create a footnote insert the following where you want the footnote number in the text (with your text between the quotes):
<?php footnote("footnote text here") ?>
That's it.
You can embellish the script as desired. For example, to pop up the footnote text as a tooltip, add title="$footnote" to the tag. You can also put a table tag, etc, in the printing function to make the footnote numbers and text line up nicely.
Here is my page explaining line by line how the script works. It also has an embellished version with the features mentioned above.
https://vocademy.net/textbooks/WebDatabase/Footnotes/PageSetup.php?Page=3&CourseDirectory=WebDatabase

How to output data after all php is executed?

I am creating breadcrumbs on my simple site.
I have some helper classes. I use them like this (just example):
$Breadcrumbs = new Breadcrumbs();
$Breadcrumbs->add(new Breadcrumb("/", "page1"));
$Breadcrumbs->add(new Breadcrumb("/", "page2"));
$Breadcrumbs->add(new Breadcrumb("/", "page3"));
$breadcrumb->show(); returns this:
<ol class="breadcrumb">
<li>page1</li>
<li>page2</li>
<li class="active">page3</li>
</ol>
So, in my project I have some switch-case constructions in which I include some files.
In this files I am using $breadcrumbs->add(...). This code:
<div class="container body">
<? $Breadcrumbs->show();?>
<?
$page = isset($_GET['page']) ? $_GET['page'] : null;
switch($page):
case "suppliers":
require_once($DOCUMENT_ROOT."/modules/suppliers.php");
break;
default:
require_once($DOCUMENT_ROOT."/modules/default.php");
break;
endswitch;
?>
<? $Breadcrumbs->show();?>
</div>
gives me this result:
Well, it works like it must work. I am using $breadcrumbs->add(...) in require files after I called $breadcrumb->show() first time thats why 1st call returns blank result. 2nd call of show() is after all breadcrumbs are added, so it returns fine result.
The questions is how to output breadcrumbs before switch blocks but with right content. Maybe I need a buffer or idk?
This is a good example of why it is such a good idea to separate out logic from presentation: you have a nice abstraction for crumb links, but can't use it properly because your other code is outputting as it goes along, rather than working with abstract data.
Obviously, you could throw away your current structure and port both logic and display directly into a new framework, but assuming you want to migrate from where you are now, here's one approach:
Create an object or array that represents the "result" of whatever module is called. Replace all current use of echo or ?> with concatenation to a string called something like $results['generic_output']. This is effectively like buffering your output, and is enough to let you use your existing abstractions like $breadcrumbs at any time. At this stage, your "template" would consist mostly of echo $results['generic_output'], plus the boilerplate header and footer which is probably already gathered in one place.
Start breaking down the output into sections. Particularly look for sections which are similar on multiple pages. For instance, if you have a "sidebar" with different content on each page but similar styling, make a $results['sidebar_content'] with just the content of that sidebar; the boilerplate to lay it out can then go into your template, and you've reduced the amount of code duplication.
Make the data you pass to the template increasingly abstract, with the goal of eventually having no HTML outside of the template(s). For instance, maybe the sidebar is made up of panels; you might start with an array of HTML blocks, one for each panel, but then turn it into an array of objects based on the actual data being displayed (say, a special offer, or the customer's current basket), with a set of templates for handling different kinds of panel. Eventually, it should be theoretically possible to build a plain-text version of your site with no HTML, just by changing the template layer, and none of the original modules.
The final step is to separate decisions about what to show from decisions about what to do. Continuing with my imaginary sidebar, your template could always receive the current basket as a general variable for use somewhere on the page, rather than as "sidebar item 1". This allows you to completely separate the actions that led into a page from the output that eventually results.
I would like to stress that this is not the way to a perfect framework, or the definitive solution to your situation, but it's one way of organising existing code (and existing thinking) in the right direction.
In the above, the "templates" could just be a set of PHP files using ?> or echo to produce the output, or it could be a dedicated templating system such as Smarty or Twig. Indeed, the point of the separation is that you could change your mind on that front later, because the result of the code modules would be an array of data to be displayed, which is just what Smarty or Twig would need as input.

Apply a class to a <h1> based on the site url

I'm new to PHP and want to apply a specific class to the title of my page depending on what part of the site the viewer is browsing.
For instance, I want to apply the class "blog" to the if the viewer is at domain.com/blog OR domain.com/blog/post-1 so on and so forth BUT apply the class "pics" if they're viewing domain.com/pics or domain.com/pics/gallery-1 etc etc.
I found something that could be modified to serve my needs using javascript here
but I figured seeing as I'm using PHP already, it'd make more sense to keep this sort of thing server side.
As I say, I'm new to PHP. I've experimented with some regular expressions, but to no avail.
EDIT: Sorry not to be more specific in my first post, I am using wordpress as my CMS - this is my first stackoverflow post, I trust you can forgive me :)
<?php
if (substr($_SERVER['REQUEST_URI'], 0,5)=='/pics') {
$h1class='someclass';
}
The it depends on how you're putting the class in the tag, might be like this
?><h1 class="<?php echo $h1class; ?>">...
Rather than putting a class in based on the page, I would suggest having seperate CSS files for home.css, blog.css, whateverelse.css. Of course, these would be in addition to some sort of default.css or site.css or whatever that would contain the styles used across the site.
You can then build a function/method to create the CSS calls in the HTML header. I usually have a "Page" object that builds the actual HTML page, and a "get_css" method that spits out the CSS calls.
It's hard to get more specific without knowing how you currently build pages.
Here is the solution I ended up crafting. Credit to #m.buettner for pointing me towards explode().
<h1 id="title-text" class="
<?php #returns the category as a class
$url = array();
$url = explode('/', get_permalink());
echo $url[3];
?>
mono in-case-404">
SITE
</h1>

What is the best practice to use when using PHP and HTML?

I have been designing websites for a while now, but there is one thing that I have never been quite sure of when using PHP and HTML. Is it better to have the whole document in PHP and echo HTML like so:
<?php
doSomething();
echo "<div id=\"some_div\">Content</div>";
?>
Or have a HTML file like so and just add in the PHP:
<html>
<body>
<?php doSomething(); ?>
<div id="some_div">Content</div>
</body>
</html>
It seems tidier to echo HTML, especially if lots of PHP gets used throughout the page, but doing so loses all formatting of the HTML i.e. colors in the IDE etc.
There are varying opinions on this. I think there are two good ways:
Use a templating engine like Smarty that completely separates code and presentation.
Use your second example, but when mixing PHP into HTML, only output variables. Do all the code logic in one block before outputting anything, or a separate file. Like so:
<?php $content = doSomething();
// complex calculations
?>
<html>
<body>
<?php echo $content; ?>
<div id="some_div">Content</div>
</body>
</html>
Most full-fledged application frameworks bring their own styles of doing this; in that case, it's usually best to follow the style provided.
I think this would depend on your group's or your own decided convention. And it can and should vary depending on what type of file you're working in. If you follow the MVC pattern then your views should be the latter. If you're writing a class or some non-output script/code then you should use the former.
Try to keep a separation of display or formatting of output and the logic that provides the data. For instance let's say you need to make a quick page that runs a simple query and outputs some data. In this case (where there is no other existing infrastructure or framework) you could place the logic in an include or in the top or the bottom of the file. Example:
<?php
# define some functions here that provide data in a raw format
?>
<html>
<body>
<?php foreach($foo = data_function($some_parameter) as $key => $value): ?>
<p>
<?=$value;?>
</p>
<?php endforeach; ?>
</body>
</html>
Or you could place the logic and function definitions in an include file or at the bottom of the file.
Now if you're producing some sort of class that has output (it really shouldn't) then you would echo the HTML or return it from the method being called. Preferably return it so that it can be output whenever and however the implementer would like.
The syntax highlighting is an important benefit of the second method, as you said. But also, if you're following good practices where logic and presentation are separated, you will naturally find that your files that contain HTML are almost entirely HTML, which then, naturally, leads to your second method again. This is the standard for MVC frameworks and the like. You'll have a bunch of files that are all PHP, doing logic, and then when that's done they'll include a presentation file which is mostly HTML with a sprinkling of PHP.
Simple:
More PHP - close HTML in PHP. When you generate HTML code in PHP, when you are doing something like a class, so it is better to make it in echo.
Less PHP - close PHP in HTML. This is stuff like just putting vars into fields of HTML stuff, like forms... And such.
The best approach is to separate the HTML from the PHP using template system or at least some kind of HTML skeleton like:
<main>
<header/>
<top-nav/>
<left-col>
<body />
</left-col>
<right-col />
<footer/>
</main>
Each node represents a template file e.g. main.php, hrader.php and so on. Than you have to separate the PHP code from the templates as something like functions.php and fineally use your second approach for template files and keeping functions clean of "echos" and HTML.
If you can, use a template engine instead.
Although it is slightly easier at first to mix your HTML and PHP, separating them makes things much easier to maintain later on.
I would recommend checking out TemplateLite which is based on Smarty but is a little more light weight.
I've reached a conclusion that using views in MVC framework e.g. Laravel, Yii, CodeIgniter is the best approach even if you are not displaying the html straight away.
Inside the view do all the echoing and looping of prepared variables, don't create or call functions there, unless formatting existing data e.g. date to specific format date('Y-m-d', strtodate(123456789)). It should be used only for creating HTML, not processing it. That's what frameworks have controllers for.
If using plain PHP, create you own view function to pass 3 variables to - html file, array of variables, and if you want to get output as string or print it straight away for the browser. I don't find a need for it as using frameworks is pretty much a standard. (I might improve the answer in the future by creating the function to get view generated HTML) Please see added edit below as a sample.
Frameworks allow you to get the HTML of the view instead of displaying it. So if you need to generate separate tables or other elements, pass the variables to a view, and return HTML.
Different fremeworks may use various type of templating languages e.g. blade. They help formatting the data, and essentially make templates easier to work with. It's also not necessary to use them for displaying data, or if forced to use it by the framework, just do required processing before posting the variables, and just "print" it using something like {{ yourVariable }} or {{ yourVariable.someProperty }}
Edit: here's a plain PHP (not framework PHP) - simple-php-view repository as a sample view library that allows to generate HTML using variables. Could be suitable for school/university projects or such where frameworks may not be allowed.
The repository allows to generate HTML at any time by calling a function and passing required variables to it, similar to frameworks. Separately generated HTML can then be combined by another view.
It depends on the context. If you are outputting a lot of HTML with attributes, you're going to get sick of escaping the quotation marks in PHP strings. However, there is no need to use ?><p><? instead of echo "<p>"; either. It's really just a matter of personal taste.
The second method is what I usually use. And it was the default method for me too. It is just to handy to get php to work inside html rather than echo out the html code. But I had to modify the httpd.conf file as my server just commented out the php code.

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>

Categories