PHP MVC - handling views - php

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.

Related

Pros and Cons: Writing HTML in PHP

(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.

Help getting started with OO PHP & MySQL

I have been writing a lot of code for work in PHP/MySQL. So far it has all been procedural making use of functions for functionality occuring multiple times/places. Starting to find some of the site hard to manage - time to go OO.
I want to learn about MVC with object oriented PHP & MySQL. I have some experience in Java and MVC but never anything to do with web technologies, i.e. HTML/CSS/JS etc. I don't really understand how the dynamically generated HTML fits in with the classes etc.
I am after some recommndations about where I can start. Ideally some sites with great examples from the ground up. I don't really want to use a framework at this point because I find that it does too much for you. Once I understand the OO approach with MVC I'll probably use a framework to managei easier.
Cheers,
Evan
You have a lot of code, and despite being hard to change, it probably works. Making an overhaul is going to set you back a while, so the best approach is incremental. Find some ONE thing that would seriously benefit from using objects, and use objects there. Refactor as you are able to run tests. You can work this in with the ordinary flow of events, and things work out OK.
Frankly, if you're serious about removing redundancy and duplication, you'll often find places where just writing a small function can make a dent. If you do this often enough, you'll find groups of functions that work on the same data. That will suggest where to look for objects.
In other words, if you listen with the right kind of ears, the code will tell you.
If you just want a good online course, maybe you should have a look at
http://www.lynda.com/home/DisplayCourse.aspx?lpk2=653&srchtrk=index%3A1%0Alinktypeid%3A2%0Aq%3APHP%20Object%20Oriented%0Apage%3A1%0As%3Arelevance%0Asa%3Atrue%0Aproducttypeid%3A2%0Acategory_facet%3APHP
This course was really useful for a friend of me. The progress he booked when he finished this tutorial was really great. It takes you through the basics of building a CMS in PHP and object oriented.
I think you should start with small pieces to get into OOP step by step. I mean that you should write simple classes for things you use often like handling forms, image uploads, site messages, session handling.
When you get used to programming classes and working on objects it will be time to jump for something bigger like refactor whole "engine" to OOP using mvc and other stuff.
Not really an answer but too big to be a comment.
Actually HTML has nothing to so with classes and JS and CSS has nothing to do with PHP, MVC and OOP at all.
Your code should produce some data which is going to be displayed one or another way. You can use some class to render this data, but it's not that important class.
While JS and CSS are totally separate files usually, called by browser directly from the server, avoiding your application code (unless being generated dynamically). Anyway you should have not too much concern in it.
Although it's still hard and non-trivial task to tie classes hierarchy with such a discrete way of execution of a typical PHP application. Once wise man have said once, "If Windows were have to restart after each user's click, it were written completely different".
welcome to SO.
I am by no means a PHP expert, here is my thought comes on top of my head:
OO programming with PHP does help, but not very likely as the rescue to removing all the redundancies or making your code "neater". The traditional way of coding in PHP can produce nice code. OO helps to encapsulate your code to hide the implementation and reuse others' code by direct composition and/or via inheritance.
I would say the real concern here is how to decouple the "static" html from the "dynamic" PHP.
For instance, there shouldn't be many :
echo "<h1>A title</h1";
echo "<p>blah blah blah...";
Even in conditional printing.
I would say separate the whole business logic on one page/script into several functions, and at least hide the nitty-gritty inside a function.
For your questions on popular OO frameworks of PHP, CakePHP is a good one, got its inspiration from Ruby on Rails.
Read MVC Tutorial in PHP to understand what MVC is then start using a MVC Framework like Zend, CakePHP, Symphony or CodeIgniter...

A Question About Embedding HTML In PHP

Some time ago I read a posting on a board where the person was talking poorly about people that have HTML embedded/within their PHP. I do quite a bit of PHP development but I still interleave HTML and PHP in the same document. Is there a better way to do this, am I doing it wrong? I know that in JSP/JSF they use an XML document with namespaces to insert their HTML code so I was wondering if there was a similar function that PHP uses that I should be taking advantage of.
Thanks for taking the time to read. :-)
PHP was originally designed as a templatng language. It sort of evolved over time to give it more power, but that doesn't mean you can't still use it for templating. A few <?=$var?>s here an there isn't too awful; hardly worse than {{var}} or whatever other syntax these new fangled engines offer.
The thing you really should do though, is take as much "business logic" out of the "views" as possible. That means the only code on the display page should be stuff that's actually relevant to how the page looks. No database updates or stuff like that. If you do this, then it should have nice, clean, maintainable pages :) No framework or anything necessary.
That said, I'd only do this for smaller apps. Template engines don't hurt either ;) Especially if your designer is a non-programmer.
Yes. You could separate the presentation code into different files. They call them views, or templates. There are a pretty bunch of templating engines you could use: there's smarty, there's Twig, and a lot of others.
You could also use a full-featured framework, like Zend, Symfony, CakePHP, Code Igniter etc. There's a lot of lists floating around.
Best regards,
T.
You should consider using a template engine such as Smarty instead of mixing logic and presentation. This clears up both code and page, and forces you to define your requirements for the page clearly before invoking the template engine.

PHP: Separating Business logic and Presentational logic, is it worth it? [duplicate]

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.

To use views or not to use views

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.'

Categories