(I'm using google translate)
I separate my HTML and PHP, just for good programming practices in MVC.
However a lot of the time I come across someone on staff writing HTML directly in a PHP file.
And during the discussion of 'don't do that, it's bad, it's not a good practice', I haven't got any technical arguments, apart from 'it's not good practice'.
And they always say, 'I am not bound to get stuck on details."
Technically, because it isn't recommended?
It is not recommended because the past has shown that the longer a routine or script grows, the harder it is to manage. If you need to deal with HTML and PHP in one file, you need to write more than if you would have separated the code into two. Which brings me to the point that you write more in one file with HTML and PHP which results in more complex code.
This is only general. There are programmers out there who don't have a problem with larger code-chunks and who don't have a problem with mixing languages in the same files.
At first sight it might even look easier. However, as software tends to become more complex as it grows, after some time of growth it's worth to think about how to modularize the code, e.g. to separate the view from request processing.
One common line that is drawn between components is then between the output (display) and the processing. The processing will interface with the output layer then instead of having both jobs in one script/routine (processing and display of output). Actually the output is factually abstracted / normalized / reduced to make the output code work on it on it's own. E.g. instead of outputting HTML to the browser, the processing will pass objects to the output layer and the output layer will convert it into HTML then (the meaning of object is broad here, can be a variable, an array or an OOP object).
If you are developing together with someone else, you should decide together where to draw these lines so you can actually work together. You're both doing something wrong because like you write in your question it's not clear how you can work together. Working together is more crucial than favouring one design over the other. If you think your colleague is wrong, you both need to discuss the issue.
In my opinion you can think about it like this.
If the PHP-code is related to how the information is being displayed to the user, then it is OK to have it in the view (if you are using an MVC approach) or mixed in with the HTML. Sometimes you need small pieces of code to display the information as you want, "if this date is passed then show it like this, otherwise show it like that".
In any other case, you should avoid mixing your PHP with your HTML, for the purpose of structure, ease of maintenance, DRY and so on.
Related
I've found a framework that handles the views in a different way than just plain html. To be honest, I've no idea how are the big frameworks handling this issue because I've mostly worked with some tiny frameworks, so that's why it was an interesting thing for me. A quick example:
Instead of writing
<h2>Click on this example</h2>
You'd have to type
echo $html->h2('Click on this' . $html->link('www.example.com', 'example'));
So, my question is which one is better? Isn't plain html going to be faster? And let's say more understandable for others? Or let's leave the understandable part away, I want to know more about the performance and maybe other stuff that people know and can be mentioned on this issue.
As everything in the programming world, it's a matter of taste.
Though, I'm strongly against it, for a few reasons:
It makes writing your views harder for non-PHP-programmers.
Annoying to debug later on
I like to see my views the same way as the browser will.
Adds a lot of overhead to pretty simple stuff
Looses the pretty (and logical) HTML indentation
UGLY!
HTML issues are easy to spot anyways, if you are indenting your HTML markup correctly.
So for me - plain HTML all the way.
Though, some view helpers are great - creating links, handling element classes, validation, etc.
In my opinion, try to find the sweet spot - don't clutter your view with too much PHP, but don't give up on making sure your code is as dynamic as it could be.
You just cant say so... Usually, MVC framework divides codes into modules which makes the site clean by separating database actions, logical actions and views. There are also other cases like sending mails, paginations, image processing and manipulations etc which are complex tasks in plain programming and can be done in few lines in MVC because every thing is predefined. The example you defined above is only to follow the pattern but you can use it other way too.. So, it an alternate. You can use it either way. so, whenever you find that in certain cases the MVC could be complex, you can do that in your own way. So, I guess its more flexible by giving us the option of both ways.
Hope that answers your question.
I have personally worked with the Yii PHP Framework, and even that has its way of handling HTML views(CHtml), though it was my choice to use either. The interpretation that rendering plain HTML is faster than writing it in some code which is interpreted by the framework and then generated as HTML make sense, and as a matter of fact, I do think plain HTML is faster.
However this allows better flexibility in creation of dynamic HTML content, like form support methods (validation, etc..), and other helper methods. Also I think this has evolved more from the Object Oriented Programming obsession.
But it'll only be a matter of time before you get used to it. And if you think about performance, think that it isn't really going to make a difference.
CodeIgniter is one of the frameworks that provides an HTML helper to allow you to generate HTML through PHP code (like the latter case in your question).
While this will be marginally slower, the advantage is it ensures valid HTML is output. Take this example:
<h2>This is a header without a closing tag
The above is a common mistake which will fail silently. However, you cannot make the same mistake if you use the HTML helper function
echo heading('This is a header',2);
As for readability, anyone familiar with PHP should be able to understand either code fragment with little to no difficulty.
What are the advantages and disadvantages of separating PHP and HTML content?
The advantages mostly pertain to code readability, which in large applications plays a huge part in the maintenance of the application.
The disadvantages are that it sometimes makes advanced functionality hard to execute. Most of the time, it can be done and still keep the two separate, but it's often much simpler and easier to just insert php snippets into html code or vice-versa if its just a small amount of code.
It's a trade off between ease of execution in certain cases and readability. For the most part, I would recommend trying to keep them separate.
HTML is just for the representation of your results / forms etc (your view), see MVC pattern for more info.
If you separate it from your business logic, you'll be able to generate other views easily (e.g. JSON for Javascript).
If you're using a templating engine as well, your HTML/CSS gurus can work on the look and feel independently as well.
Separating program logic (the PHP part) from presentation (the HTML part) is beneficial for several reasons:
It allows you to change the presentation without affecting the program's inner workings, that is, you're not altering what it does by changing the layout
It allows for independent testing of both parts: you can execute parts of the program logic from a test script and inspect the results, which means you can automate a large portion of your testing
Maintenance becomes much easier, because you have less code to look through when looking for errors
For larger teams, the application can be structured in a way that allows designers (that is, people with little understanding of programming) to alter the HTML part independently without much risk of breaking the program logic
It enables you to focus on one problem at a time. You don't want to burden your mind with HTML details while debugging algorithms, and vv.
Code reuse: If your presentation layer delegates its calls to the logic layer, instead of doing it itself, chances are you'll be reusing that logic elsewhere; having it in the logic layer means you can just call it instead of copy-pasting all over the place (which in turn leads to maintenance nightmares)
There is a great advantage to separating the two because you can edit html code without breaking the PHP code. Smarty is a good template engine to learn.
The main reason is your code will be ugly if you merge those php (business logic) with the html (presentation) together, which in turn become hard to read and become hard to maintain. It won't be a problem if your web application is a simple one. But if it's a enterprise scale project, maintaining this merged code will be a nightmare for anyone.
Beside, the kind of programming you do
for each part and sometimes the
language you do it in are different.
Separating the two allows one to use
the best tools for that particular
part.
source: http://www.paragoncorporation.com/ArticleDetail.aspx?ArticleID=21
if u want to divide the php code and html, use any php frameworks, such as codeigniter, cakephp, zend, yii, etc., the main advantage is, if ur going to change the site design not your functionality, at that time it will be very useful and also we can develop the code in reusable manner.
I'm creating a PHP file that does 2 mysql database calls and the rest of the script is if statements for things like file_exists and other simple variables. I have about 2000 lines of code in this file so far.
Is it better practice to include a separate file if a statement is true; or simply type the code directly in the if statement itself?
Is their a maximum number of lines of code for a single file that should be adhered to with PHP?
I would say there should not be any performance issue related to the number of lines in your php files, it can be as big as you need.
Now, for the patterns and best practices, I would say that you have to judge by yourself, I saw many well organized files of several thousand lines and a lot of actually small and difficult to read files.
My advise would be:
Judge the readability of the source code, always organize it well.
It's important to have a logical separation to some extent, if your file does both: heavy database access, writing, modification, html rendering, ajax and so on.. You may want to separate things or use object oriented approach.
Always search the balance between the logical separation and code. It should not be messy nor extra-neat with a lot of 10-line files
2000 lines of code in a single file is not exactly bad from a computer point of view but in most situations is probably avoidable, take a look into the MVC design pattern, it'll help you to better organize your code.
Also, bear in mind that including (a lot of) files will slow down the execution of your code.
You may want to read a book like Clean Code by Bob Martin. Here are a few nuggets from that book:
A class should have one responsibility
A function should do one thing and do it well
With PHP, if you aren't using the Class approach; you're going to run into duplication problems. Do yourself a favor and do some reading on the subject; it'll save you a lot more time in extending and maintenance.
Line count is not a good indicator of performance. Make sure that your code is organized efficiently, divided into logical classes or blocks and that you don't combine unrelated code into single modules.
One of the problems with a language like PHP is that, barring some creative caching, every line of every included file must be tokenized, zipped through a parse tree and turned into meaningful instructions every time the hosting page is requested. Compiled platforms like .NET and Java do not suffer from this performance killer.
Also, since one of the other posters mentioned MVC as a way to keep files short: good code organization is a function of experience and common sense and is in no way tied to any particular pattern or architecture. MVC is interesting, but isn't a solution to this problem.
Do you need to focus on the number of lines? No, not necessarily. Just make sure your code is organized, efficient, and not unnecessarily verbose.
It really doesn't matter, so long as you have documented your code properly, modularised as much as possible, and checked for any inefficiencies. You may well have a 10,000 line file. Although I usually split at around 500-1000 for each section of an application.
2k lines sound too much to me... Though it depends what code style you are following, e.g. many linebreaks, many little functions or good api-contract comments can increase the size though they are good practice. Also good code formatting can increase lines.
Regarding PHP it would be good to know: Is it 2k lines with just one class or just one big include with non-OOP PHP code? Is it mixed with template statements and programm logic (like I find often in PHP code)?
Usually I don't count these lines, when to split. They just went into habits. If code gets confusing I react and refactor. Still having looked into some code we as a team wrote recently, I can see some patterns:
extract function/method if size is bigger than 20LOC (without comments) and usage of if/else clauses
extract to another class if size >200-300LOC
extract to another package/folder if artifacts >10
Still it depends what the kind of code I have. For instance if loads of logic is involved (if/else/switch/for), the LOC per function decreases. If there is hardly any logic involved (simple stupid one-path code statements) the limits increase. In the end the most-important rule is: Would a human understand the code. Will she/he be able to read it well.
I don't know any useful way to split code that's that simple, particularly if it all belongs together semantically.
It is probably more interesting to think about whether you can eliminate some of the code by refactoring. For example, if you often use a particular combination of checks with slightly different variables, it might help to outsource the combination of checks into a function and call it wherever appropriate.
I remember seeing a project once that was well-written for the most part, but it had a problem of that kind. For example, the code for parsing its configuration file was duplicated like this:
if (file_exists("configfile")) {
/* tons of code here */
} else if (file_exists("/etc/configfile")) {
/* almost the same code again */
}
That's an extreme example but you get the idea.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Why should I use templating system in PHP?
I was just curious as to how many developers actually do this?
Up to this time I haven't and I was just curious to whether it really helps make things look cleaner and easier to follow. I've heard using template engines like Smarty help out, but I've also heard the opposite. That they just create unnecessary overhead and it's essentially like learning a new language.
Does anyone here have experience with templates? What are your feelings on them? Are the helpful on big projects or just a waste of time?
On a side note: The company I work for doesn't have a designer, there are just two developers working on this project charged with the re-design/upgrade. I also use a bit of AJAX, would this have issues with a template engine?
Not only does this practice make the code look cleaner, it also has many long term and short term benefits.
You can never go wrong with organizing code. First off it makes it much easier to maintain and easier to read if someone else has to pick up after you. I have worked with Smarty before and it is nice, it keeps the designers work from interfering with the program code.
Using template systems and frameworks would make it much easier to accomplish tasks. There is a rule of thumb you can follow which is DRY (Don't Repeat Yourself). Frameworks help you achieve this goal.
You may want to look into MVC, this is the model that these frameworks are based off of. But you could implement this design structure without necessarily using framework. Avoiding the learning curve. For frameworks like Zend, the learning curve is much greater than some other ones.
I have found that Code Igniter is fairly easy to use and they have some VERY helpful video tutorials on their website.
Best of Luck!!
Actually it's the business logic that needs to be separated from the views. You can use php as a "template language" inside the views.
You can use ajax on any template engine i think.
Edit
My original response addressed the question whether to use a template engine or not to generate your html.
I argued that php is good enough for template tasks, as long as you separate business logic from presentation logic.
It's worth doing this even for simple pages, because it enables you to:
isolate the code that is the brain of your application from the code that is the face, and so you can change the face, without messing with the brain, or you can enhance the brain without braking the looks
isolate 80% of bugs in 20% of your code
create reusable components: you could assign different presentation code to the same business code, and vice versa;
separate concerns of the feature requests (business code) from the concerns of the design requests (presentation code), which also usually are related to different people on the client side, and different people on the contractor side
use different people to write the business code and the presentation code; you can have the designer to handle directly the presentation code, with minimal php knoledge;
A simple solution, which mimics MVC and doesn't use objects could be:
use a single controller php file, which receives all requests via a .httpdaccess file;
the controller decides what business and presentation code to use, depending on the request
the controller then uses an include statement to include the business php file
the business code does it's magic, and then includes the presentation php file
PHP is a template engine (or if you prefer, a hypertext preprocessor). When HTML is mixed heavily with PHP logic, it does become very difficult to maintain, which is why you would have functions defined separately to build various parts and simply build the page from short function calls embedded in the HTML. Done like this, I don't see much of a difference between Smarty and raw PHP, other than the choice of delimiters.
Separation of concerns is a very important tenant to any type of software development, even on the web. Too many times I have found that people just throw everything into as few files as possible and call it a day. This is most certainly the wrong way to do it. As has been mentioned, it will help with maintainability of the code for others, but more than that, it helps you be able to read the code. When everything is separated out, you can think about easily.
Code Ignitor, I have found, has been the easiest to learn framework for working with PHP. I pretty much started my current job and was up and running with it within a few days, from never having heard of it, to using it pretty efficiently. I don't see it as another language at all, either. Basically, using the framework forces me to organize things in a manageable way, and the added functionality is anlagous to using plugins and such for jQuery, or importing packages in Java. The thought that it's like learning another language seems almost silly.
So, in short, organize organize organize. Keep in mind, though, that there is a level of abstraction that just becomes absurd. A rule of thumb is that a class (or file in our case) should do one thing very well. This doesn't mean it is a class that wraps around print, but takes a string, formats it using a complex algorithm and then prints it (this is just an example). Each class should do something specific, and you can do that without any framework. What makes MVC great, though, is that it lets you organize things further, not just on the single class level, but on the level of "packages", being Model, View, and Controller (at least in the case of these frameworks; there are other ways to package projects). So, now you have single classes that do things well, and then you have them grouped with similar classes that do other things well. This way, everything is kept very clean an manageable.
The last level to think about once you have things organized into classes, and then packages, is how these classes get accessed between packages. When using MVC, the access usually will go Model<->Controller<->View, thus separating the model (which is usually database stuff and "business" code in the PHP world), from the view (which usually takes information from the user, and passes it along to the controller, who will then get more information from the model, if necessary, or do something else with the input information). The controller kind of works like the switchboard between the two other packages usually. Again, there are other ways to go with packaging and such, but this is a common way.
I hope that helps.
Smarty and other php template frameworks really do nothing more than compile to PHP anyway, and they also cache their results in most cases to allow for faster processing. You can do this all on your own, but if you ever look at the compiled templates that Smarty generates, and compare to the original Smarty template you create, you can see that one is far more readable than the other.
I write mostly mod_perl these days and started using templates (HTML::Template) halfway through our ongoing project. If I had to make the decision again, I would use templates right from the start - rewriting later to use templates is kind of tedious, though rewarding because you get nicer and cleaner code. For anything bigger than 2-3 pages in php, I would also use some template engine.
One big advantage of a templating engine such as Smarty is that non-developers can use it to embed the necessary logic that is used on the front-end (one really can't separate logic and display on all but the simplest sites). However, if the developer is the one maintaining the pages then using PHP would be preferable in my opinion.
If you separate out large logic blocks and maintain a consistent patten for looping and for-each flow control statements (i.e. don't use print statements, or only use print statements for one-liners, etc.) Then that should be okay.
I seem right now to be embroiled in a debate with another programmer on this project who thinks that views have no merits. He proposes a system that PHP looks something like this:
$draw = new Draw;
$nav = $draw->wideHeaderBox().
$draw->left().
$draw->image().
Image::get($image,60,array('id'=>'header_image')).
$draw->imageEnd().
$draw->leftEnd().
$draw->left(10).
'<div id="header_text">'.
self::defaultSectionText().
'</div>'.
$draw->leftEnd().
and so on (this is in the controller btw). Now his arguments for this actually make some sense, he claims that if there is a redesign all we need to do is change the HTML in one place and it changes everywhere automatically. For some reason however, this method still rubs me the wrong way, is there any merit to views over this method? I mean besides not having to retype HTML by hand.
HTML time-savers are useful, but they're only useful when they're intuitive and easy-to-understand. Having to instantiate a new Draw just doesn't sound very natural. Furthermore, wideHeaderBox and left will only have significance to someone who intimately knows the system. And what if there is a redesign, like your co-worker muses? What if the wideHeaderBox becomes very narrow? Will you change the markup (and styles, presumable) generated by the PHP method but leave a very inaccurate method name to call the code?
If you guys just have to use HTML generation, you should use it interspersed in view files, and you should use it where it's really necessary/useful, such as something like this:
HTML::link("Wikipedia", "http://en.wikipedia.org");
HTML::bulleted_list(array(
HTML::list_item("Dogs"),
HTML::list_item("Cats"),
HTML::list_item("Armadillos")
));
In the above example, the method names actually make sense to people who aren't familiar with your system. They'll also make more sense to you guys when you go back into a seldom-visited file and wonder what the heck you were doing.
The argument he uses is the argument you need to have views. Both result in only changing it in one place. However, in his version, you are mixing view markup with business code.
I would suggest using more of a templated design. Do all your business logic in the PHP, setup all variables that are needed by your page. Then just have your page markup reference those variables (and deal with no business logic whatsoever).
Have you looked at smarty? http://smarty.php.net
I've done something like that in the past, and it was a waste of time. For instance, you basically have to write wrappers for everything you can already with HTML and you WILL forget some things. When you need to change something in the layout you will think "Shoot, I forgot about that..now I gotta code another method or add another parameter".
Ultimately, you will have a huge collection of functions/classes that generate HTML which nobody will know or remember how to use months from now. New developers will curse you for using this system, since they will have to learn it before changing anything. In contrast, more people probably know HTML than your abstract HTML drawing classes...and sometimes you just gotta get your hands dirty with pure HTML!
It looks pretty verbose and hard to follow to be honest and some of the code looks like it is very much layout information.
We always try to split the logic from the output as much as possible. However, it is often the case that the view and data are very tightly linked with both part dictating how the other should be (eg, in a simple e-commerce site, you may decide you want to start showing stock levels next to each product, which would obviously involve changing the view to add appropriate html for this, and the business logic to go and figure out a value for the stock).
If the thought of maintaining 2 files to do this is too much to handle, try splitting things into a "Gather data" part and a "Display View" part, getting you most of the benefits without increasing the number of files you need to manage.
I always find it much easier to work directly with html. Theres one less abstraction layer (html -> actual webpage / php function -> html -> actual webpage) to deal with then you just work in HTML.
I really think the 'just have to change it in one place' thing wont work in this case. This is because they'll be so many times when you want to change the output of a function, but only in just one place. Sure you can use arguments but you'll soon end up with some functions having like a dozen arguments. Yuck.
Bear in mind templating languages / systems often let you include sub templates, allowing you to have some reusable blocks of html.
The bottom line is if I had just started at your company and saw code like that everywhere, my first thought would be, 'Damn it! Need a new job again.'