Proper PHP syntax and practices

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 12321 Views - Last Post: 16 January 2013 - 05:23 PM

#1 Nykc  Icon User is offline

  • Gentleman of Leisure
  • member icon

Reputation: 725
  • View blog
  • Posts: 8,638
  • Joined: 14-September 07

Proper PHP syntax and practices

Post icon  Posted 13 January 2013 - 09:17 AM

I have been finding myself resorting back to PHP lately for back-end web development. I have been reading several books and playing around with different scripts etc.. One thing I have noticed since shying away from the simpleness of Wordpress is that PHP is not written in a consistent fashion. Some people use short tags <? ?> (which are discouraged, but I rarely see the proper tags in the code I debug)

Also I tend to see
<html>
   <head>
     <title><?php echo $title; ?></title>
     // More HTML header information
   </head>
   <body>
   <?php include('header.php');?>
   </body>
</html>



In a similar fashion - opening and closing so as not to parse the entire file. But I also know that some developers prefer to open the file: <?php and then not close it...

My question is in your opinions - what is the PROPER, or most preferred way to structure your documents. It can be quite annoying to have 7-8 echo statements, or php calls in a file - but what type of performance hit would parsing the entire document take? Do most professional developers prefer to insert the <?php tags only when necessary?

A lot of this can come down to developer preference, I am more concerned with best practices...

Is This A Good Question/Topic? 4
  • +

Replies To: Proper PHP syntax and practices

#2 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3637
  • View blog
  • Posts: 5,764
  • Joined: 08-June 10

Re: Proper PHP syntax and practices

Posted 13 January 2013 - 09:30 AM

It tends to be cleanest to not combine HTML and PHP at all. Instead, write template HTML files and use PHP code to import them, inject whatever values are required using string manipulation, and then echo them to the browser. There are different techniques you can use to do that, but unless you really fell like writing this yourself, I would suggest adopting a templating engine like Twig or Smarty. Using those you can completely separate the HTML and the PHP. That is one of the keys to creating well organized and easily understandable code in PHP.
Was This Post Helpful? 2
  • +
  • -

#3 Nykc  Icon User is offline

  • Gentleman of Leisure
  • member icon

Reputation: 725
  • View blog
  • Posts: 8,638
  • Joined: 14-September 07

Re: Proper PHP syntax and practices

Posted 13 January 2013 - 09:33 AM

Interesting...

With perl we use Template Toolkit and Catalyst framework - I am assuming using Twig or Smarty is a similar approach and that would make sense.

This post has been edited by Nykc: 13 January 2013 - 09:39 AM

Was This Post Helpful? 0
  • +
  • -

#4 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 782
  • View blog
  • Posts: 1,664
  • Joined: 30-January 09

Re: Proper PHP syntax and practices

Posted 13 January 2013 - 05:08 PM

The reason why people sometimes open the PHP tag without closing it is that once the tag is closed, the remaining file contents revert to HTML format. So, if you have a carriage return after the closing tag, it can insert an unwanted carriage rteurn in your HTML output. That's the reasoning, at least.

As Atli said, complete separation of HTML and PHP tends to be the cleanest method, and when you have a templating engine that reads in templates and replaces placeholders, then you need not worry about the trailing carriage return issue. Writing your own templating engine is possible, but I would not suggest it for a beginner. I have written my own framework/engine, and it took a few months (of 5-10 hours a week), and then another 6 months or so to iron out all the bugs. It's a great learning experience, but it's also very frustrating at times.
Was This Post Helpful? 4
  • +
  • -

#5 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10188
  • View blog
  • Posts: 37,629
  • Joined: 27-December 08

Re: Proper PHP syntax and practices

Posted 13 January 2013 - 07:17 PM

Prepared Statements like PDO and MySQLi will reduce the effort to guard against SQL Injection, as they are immune to it. I'd also advocate utilizing Object-Oriented Programming concepts as appropriate to help organize and modularize your code.
Was This Post Helpful? 1
  • +
  • -

#6 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 782
  • View blog
  • Posts: 1,664
  • Joined: 30-January 09

Re: Proper PHP syntax and practices

Posted 13 January 2013 - 07:46 PM

View PostNykc, on 14 January 2013 - 02:17 AM, said:

My question is in your opinions - what is the PROPER, or most preferred way to structure your documents. It can be quite annoying to have 7-8 echo statements, or php calls in a file - but what type of performance hit would parsing the entire document take? Do most professional developers prefer to insert the <?php tags only when necessary?

A lot of this can come down to developer preference, I am more concerned with best practices...

In regards to this part of your question, and I'm sure I've posted this sort of thing before in other threads (but it's worth repeating), here is in example from my new codebase, with the three parts of the recipe, Presentation layer, Logic layer and Data layer:

UsernameAnchor Template
Spoiler


UsernameAnchor Class
Spoiler


User Model method that gets called
Spoiler


And as a comparison, here's what my old code looked like, which generated a feedback log with the username anchors in it. Unfortunately this is as close as I got to hving a separate generator for username anchors - embedded in another function. There was no encapsulation at all so I never had a way of generating just the username anchor. I shudder at my old code, anyhow, brace yourself:
Spoiler


Never mind the use of globals, SELECT*s, lack of validation etc., look at how readable the first lot of code is compared to this second lot. The first lot is much easier to read, because it is completely code separated. The only part of the first lot that isn't separated out completely is the SQL statement, as I plan on moving all non-ad-hoc statements to stored procedures in the DB. Nonetheless, it is a piece of cake to see what is going on. The second lot of code on ther other hand is a nightmare.
Was This Post Helpful? 3
  • +
  • -

#7 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3637
  • View blog
  • Posts: 5,764
  • Joined: 08-June 10

Re: Proper PHP syntax and practices

Posted 13 January 2013 - 08:08 PM

View Poste_i_pi, on 14 January 2013 - 02:46 AM, said:

The only part of the first lot that isn't separated out completely is the SQL statement, as I plan on moving all non-ad-hoc statements to stored procedures in the DB.

You may want to consider using an ORM instead, like Doctrine. It integrates the database a lot better into the code, and removes the need to use any SQL, even simple queries to fetch views or call procedures.
Was This Post Helpful? 1
  • +
  • -

#8 RudiVisser  Icon User is offline

  • .. does not guess solutions
  • member icon

Reputation: 1001
  • View blog
  • Posts: 3,555
  • Joined: 05-June 09

Re: Proper PHP syntax and practices

Posted 15 January 2013 - 02:14 AM

View PostNykc, on 13 January 2013 - 04:17 PM, said:

Some people use short tags <? ?> (which are discouraged, but I rarely see the proper tags in the code I debug)

I'd just like to step in here regarding these tags. Since the thread appears to be talking about templates and the mixing of PHP/HTML, this is my 2c on writing templates:

Yes, short tags in the form of <? /* .. */ ?> for code blocks are discouraged, however, based on recent changes (and the sheer convenience for writing templates), I'd say that the short-output-tags (<?= $var ?>) are encouraged. They're now enabled by default (and can't be disabled) in PHP 5.4+.

Whilst some people are still going to throw around that you should write a whole template engine to do your conditionals and variable output, I simply don't see the point in incurring the overhead if you're not going to cache them, which, let's face it, 90% aren't going to cache them.

I see nothing wrong with this template, so long as your logic is kept to a controller/view model file:
<div id="this-is-awesome">
   <?= $this->awesome_text ?>
</div>


Of course it's a minimal example, but it should get my point across. In fairness, I really don't see anything wrong with short tags for templates either. I'm not talking about using them for including all of your PHP, but consider the following, which uses short tags for loops/conditionals with the alternate syntax, thus keeping it readable/modifiable by designers, not incurring any overhead of having to parse stuff out yourself.

<? if ($this->is_awesome): ?>
    <div id="this-is-awesome">
        <?= $this->awesome_text ?>
    </div>
<? else: ?>
    <div id="this-is-not-awesome">
        <? foreach ($this->not_awesome as $not_awesome): ?>
            <div><?= $not_awesome ?></div>
        <? endforeach ?>
    </div>
<? endif ?>


Of course, some people will disagree with me, but the fact is that you simply can't (unless you're preprocessing HTML server-side...) have templates without loops and conditionals... and if you're going to write a template engine that parses them out manually, well I see no benefit in this at all.

-------------------------------------------

All that said, I did write a Razor parser to actually compile back the Razor Syntax back into PHP, because I absolutely love it after working with MVC for so long now.

This post has been edited by RudiVisser: 15 January 2013 - 02:17 AM

Was This Post Helpful? 3
  • +
  • -

#9 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 782
  • View blog
  • Posts: 1,664
  • Joined: 30-January 09

Re: Proper PHP syntax and practices

Posted 15 January 2013 - 02:43 AM

View PostRudiVisser, on 15 January 2013 - 07:14 PM, said:

Of course, some people will disagree with me, but the fact is that you simply can't (unless you're preprocessing HTML server-side...) have templates without loops and conditionals... and if you're going to write a template engine that parses them out manually, well I see no benefit in this at all.

My templating engine doesn't have parsing of loops or conditionals embedded in templates. My templates are purely HTML with the exception that there are placeholders, signified by a string encased in curly braces. Sure, there are some trivial cases where it is annoying to use loops within the code, but because I've shifted the looping to the code, I can get away with complex parsing that would otherwise clutter the template. For example, here's the code to render out the content of a context menu in my code:
// Prepare the content
$contextMenuItem = Factory::Build(new ContextMenuItem());
$content = '';

// Loop through the items
foreach($menuXml->item as $item)
{
	// Generate the entry if the item is valid
	if(
		DisplayConditionValidator::Validate(
			array(
				'DisplayConditions'	=>	$item['DisplayCondition'],
				'CallingObject'		=>	&$params['CallingObject'],
			)
		) === true
	)
	{
		$contextMenuItem->SetPlaceholders(
			array(
				'pId'		=>	$item['ID'],
				'pName'		=>	$item['Name'],
			)
		);
		$content .= $contextMenuItem->Render();
	}
}


...with this being the contxt menu template, and context menu item template:
<table id="{pId}" class="ContextMenu">
    {pContextMenuItems}
</table>


<tr><td id="{pId}">{pName}</td></tr>


(Forgive the use of tables, I realise it should be an <ol>).

How would you achieve this with loops embedded in a template?
Was This Post Helpful? 0
  • +
  • -

#10 RudiVisser  Icon User is offline

  • .. does not guess solutions
  • member icon

Reputation: 1001
  • View blog
  • Posts: 3,555
  • Joined: 05-June 09

Re: Proper PHP syntax and practices

Posted 15 January 2013 - 02:53 AM

View Poste_i_pi, on 15 January 2013 - 09:43 AM, said:

How would you achieve this with loops embedded in a template?

With much less code?

<table id="<?= $this->menu->id ?>" class="ContextMenu">
<? foreach ($this->menu->items as $item): ?>
    <tr><td id="<?= $item->id ?>"><?= $item->name ?></td></tr>
<? endforeach ?>
</table>



Your display conditionals to determine which items would display (and so which would be in $this->menu->items) would be done in the backend, the view should only care about output.

This post has been edited by RudiVisser: 15 January 2013 - 02:55 AM

Was This Post Helpful? 0
  • +
  • -

#11 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 782
  • View blog
  • Posts: 1,664
  • Joined: 30-January 09

Re: Proper PHP syntax and practices

Posted 15 January 2013 - 04:19 AM

In regards to it being much less code, to be fair, you are only posting the View code and not the Controller(s) that would complement it. But I see your point, readability is improved and there is a cut-down in the amount of overall code.

I might run some tests on my side and see how it goes, but I'll probably need to use the output buffer to get it hooked up properly. Interesting...
Was This Post Helpful? 0
  • +
  • -

#12 RudiVisser  Icon User is offline

  • .. does not guess solutions
  • member icon

Reputation: 1001
  • View blog
  • Posts: 3,555
  • Joined: 05-June 09

Re: Proper PHP syntax and practices

Posted 15 January 2013 - 04:32 AM

Sorry, I wasn't calling what you did wrong. Of course this is all personal preference but I'd just see it as more efficient to do this:
$view->menu->items = [];
// Loop through the items
foreach($menuXml->item as $item)
{
	// Generate the entry if the item is valid
	if(DisplayConditionValidator::Validate(
			array(
				'DisplayConditions'	=>	$item['DisplayCondition'],
				'CallingObject'		=>	&$params['CallingObject'],
			)) === true)
	{
		$view->menu->items[] = $item;
	}
}


accompanied with:
<table id="<?= $this->menu->id ?>" class="ContextMenu">
<? foreach ($this->menu->items as $item): ?>
    <tr><td id="<?= $item['id'] ?>"><?= $item['name'] ?></td></tr>
<? endforeach ?>
</table>


That code is still somewhat smaller than the initial stuff, and removes the tag building in PHP, I don't particularly like that apart from in helper methods that are going to be used from within the template (for example <?= Html::ActionLink('Dashboard', 'Dashboard', 'Account') ?>).

Again, that's just my preference.

This post has been edited by RudiVisser: 15 January 2013 - 04:34 AM

Was This Post Helpful? 0
  • +
  • -

#13 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3637
  • View blog
  • Posts: 5,764
  • Joined: 08-June 10

Re: Proper PHP syntax and practices

Posted 15 January 2013 - 06:11 AM

View PostRudiVisser, on 15 January 2013 - 09:14 AM, said:

Whilst some people are still going to throw around that you should write a whole template engine to do your conditionals and variable output, I simply don't see the point in incurring the overhead if you're not going to cache them, which, let's face it, 90% aren't going to cache them.

I wouldn't exactly say that. Writing a whole template engine yourself is sort of redundant, seeing as we already have very powerful, and pretty easy to use, templating engines available, most of which already do compile and cache templates down to PHP code, much like the code you are hand-typing. The overhead of using those is negligible.

The PHP code you posted, for example, could be represented in Twig like this:
<table id="{{ menu.id }}" class="ContextMenu">
{% for item in menu.items %}
    <tr><td id="{{ item.id }}">{{ item.name|e }}</td></tr>
{% endfor %}
</table>


And while this seems more or less just like different syntax for what you did, it does come with a couple of advantages. The biggest one of which is that this limits the template developer to a very strict, and template specific, set of functionalities. When you're using the PHP tags as you are, a lazy template designer could easily be drawn into adding PHP code to quickly solve some issue that really aught to be solved in the controller code. With this, you don't have to be worrying about that; you can actually trust the template designers not to be poaching on your territory.

Another thing I like about Twig's syntax, specifically, is that it is based on syntax commonly used by other languages and frameworks, like the Python Django framework, and the Perl Template Toolkit Nykc mentioned. (Though, that last on is not identical but very similar.)

View PostRudiVisser, on 15 January 2013 - 09:14 AM, said:

In fairness, I really don't see anything wrong with short tags for templates either.

The problem with the short-tags isn't syntax (except for in XHTML/XML pages), but rather it's availability. If you use them, you are gambling that the server that hosts the code will always haven them enabled. Is it really that inconvenient to have to do <?php instead of <?? - As you mentioned, in PHP 5.4 the short <?= $var ?> is always available, so the only place where <?php tags would be needed in a pure PHP template would be for control structures.
Was This Post Helpful? 3
  • +
  • -

#14 RudiVisser  Icon User is offline

  • .. does not guess solutions
  • member icon

Reputation: 1001
  • View blog
  • Posts: 3,555
  • Joined: 05-June 09

Re: Proper PHP syntax and practices

Posted 15 January 2013 - 07:32 AM

View PostAtli, on 15 January 2013 - 01:11 PM, said:

I wouldn't exactly say that. Writing a whole template engine yourself is sort of redundant, seeing as we already have very powerful, and pretty easy to use, templating engines available, most of which already do compile and cache templates down to PHP code, much like the code you are hand-typing. The overhead of using those is negligible.

Don't get me wrong, as I mentioned at the end of the post I had written a Razor compiler for PHP simply because I love the syntax of that too; I guess it's the same type of love you have for Twig :)

I fully understand what you're saying regarding the templates, it generally is a whole separation of concerns matter, which is perfectly fine if you're the developer and you write your own templates. But when designers come involved, the tendency to include stuff they find online to achieve a task could certainly be misused/abused.
Was This Post Helpful? 0
  • +
  • -

#15 RyanRobinson  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 39
  • View blog
  • Posts: 227
  • Joined: 31-March 10

Re: Proper PHP syntax and practices

Posted 16 January 2013 - 06:06 AM

I am fully behind Rudi's method of writing PHP and HTML.

I do the same and I find it a really good way of sprinkling snippets of PHP around a design. This makes sure that designers can also work with the front-end. I find it really useful to actually see the design I am working on in Dreamweaver whilst I'm adding the dynamic PHP stuff.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2