PHP is easy to start with. The web page is the easiest and fastest way to see progress. And that’s why PHP is often chosen as the first programming language. In fact thanks to PHP I’ve started to work, but it’s another story 😉
The beginning
Many newbie programmers started with something like that:
<?php $name = $_GET["name"]; if ($name == "") { $name = "Stranger"; } ?> <html> <head> [...] </head> <body> <h1>hello <?php echo $name; ?></h1> </body> </html>
It’s fully functional web page! And It’s all right to start like this, but it’s very wrong to continue coding like this. Mixing HTML and PHP is just wrong (ok, PHP might be used as a template engine and I will cover that later). I think that many people call themselves “PHP programmers” after that and it’s probable source of the shortest joke in the (programming) world – PHP programmer 😉
But it’s not the way modern PHP looks like. Since PHP5 it’s fully object oriented programming language that becomes better and better each version. MVC architectural pattern is wide used and SOLID principles are applied.
Symfony2
Now look how modern website can be build using one of the most famous frameworks: Symfony2.
// HelloController.php <?php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; class HelloController extends Controller { /** * @Route("/{name}", name="homepage") * * @param string $name * @return Response */ public function indexAction($name = "Stranger") { return $this->render("AppBundle::hello.html.twig", ["name" => $name]); } }
{# hello.html.twig #} {% extends "::base.html.twig" %} {% block content %} Hello {{ name }}! {% endblock %}
{# base.html.twig #} <html> <head> [...] </head> <body> {% block content %}{% endblock %} </body> </html>
Looks much better, doesn’t it? 🙂 Just to show you what’s happening here I will briefly describe these 3 files.
Controller
In `HelloController.php` we have a namespace for this class (every class should be in separated file) which is used by classes autoloader. Next, we have imported some classes that are used in the code.
After that, there is a class definition with specified parent class Controller (which contains some basic helpers and most used methods for… controllers ;-)) and one method: `indexAction`.
Let’s take a deeper look at the action. First, we have an annotation that defines routing for this action. It contains path (`/{name}`), allowed parameter (`{name}` that later becomes `$name`) and name for the route. It’s enough for a framework to find the action and pass value after `/` to the `$name` parameter.
Next two lines are part of PHPDoc, library used for documenting code.
Every action must be public and its name should end with `Action` (it’s a part of the convention). Every parameter defined in routing has its equivalent in method parameters and has the same name. The order doesn’t matter, but names do 😉 We can specify a default value for each parameter (in this example it’s “Stranger”).
The methods body is very simple. It contains only one line – specify a template that will be used to display the web page and pass parameters to it (in this example only `$name`). That is the core of every web page. In this example, it’s very simple but it could be very complicated and use services, events, databases and anything you will need.
Templates
Next, we have two template files, one (`base.html.twig`) is the base for other templates that contains needed HTML tags, styles, js imports, etc.
The `hello.html.twig` file is very simple, it extends `base.html.twig`, uses its block `content` and writes a welcome message it there. If you know any template engine it should be familiar look, if not I will cover that later.
There are much more: routing and templates defined via annotations, classes autoloader, dependency injection, events and subscribers, ORM, etc. I will cover all of that in this series so don’t worry 🙂
Summary
I hope that this simple example gives you a quick look at the modern PHP language. I will be happy to get some feedback from you – don’t hesitate to use the comments section below. If you have some topic that you want to be described – let me know!
Don’t forget to check out other PHPhyts!
- PHPyths Buster: A great string performance test! (updated)
- PHPyths Buster: Single quotes are faster than double quotes
- PHPyths Buster: Annotations
- PHPyths Buster: End of the project
- PHPyths Buster: Displaying reminders
- PHPyths Buster: Evernote SDK [update]
- PHPyths Buster: Basic application
- PHPyths Buster: Hello World!
- PHPyths Buster: Project environment
- PHPyths Buster: The Project
If you had written it in PHP7 it would look even more modern
Thanks for comment 🙂
I plan to write a separate post about PHP7 to show, how awesome PHP is changing. But it’s a good point so I’ll consider using PHP7 in next examples 🙂
Ugly is just an opinion though; it’s incredibly subjective and that is the real problem.
I feel like one of the biggest mistakes everyone is making is assuming that anything that is not like what they do is incorrect. It’s a terrible position to come from, it’s limiting and it really helps nobody.
I’d rather hear what is actually wrong, not “I don’t like that”.
* “I’ve seen a lot of PHP code without tests” to which I’d reply “I’ve seen a lot of non-php code without tests”
* “PHP is slow” to which I’d reply “Doing nothing is very fast, have you tried that?”
* “I don’t like the language API / design”; reply “write you’re own language or contribute”
* “My module doesn’t exist”; reply “PHP can access services via established protocols and supports new functionality through PHP, Zephir and C code”
The bottom line is nothing is perfect. Languages like Java and C# and even C will have more capability because they have existed for longer. But often a deal is struck between the programmer to get up to speed with PHP because it’s easier to learn; to muddle through, accepting you will iterate and re-design later.
Great comment, thanks!
I agree, people like to criticize things that they don’t know. Or know, like in PHP example, but from several versions before. It’ll be no problem if they say “I think PHP is ugly” but they say just “PHP is ugly”. Opinion – all right, we can talk. Imperative – waste of time.
This series is inspired by .net developers met at the “Daj Się Poznać” contest. I want to show them that modern PHP is not ugly if you know what you’re doing. Everyone can write ugly code in the prettiest language in the world. But only a good programmer can write clean, pretty code no matter what language she/he uses.