Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I've been trying to find out if I can apply the MVC architecture to procedural and how I can go about implementing this into my code. From my understanding MVC basically represents the separation of the business logic, presentational layer and other logic although it always seems to be aimed at OO-PHP in particular.
Can you recommend the best way to approach MVC within a procedural context??
Thanks.
MVC is OO pattern and you want to approach it with a procedural context.
This is plain wrong. MVC has nothing to do with object oriented coding.
MVC is a software architecture pattern which aims at separating the representation of information from the user's interaction with it.
How you achieve that is up to you. You can achieve that using whatever coding form you want, object oriented, procedural, functional, and what not.
With regard to the question at hand: The easiest way to achieve the MVC pattern when you're coding procedural PHP is to use a lot of small functions where each particular function has its own unique task. Don't let a function have many tasks. That way it is more easy to separate things. Also don't keep a lot of functions in the same file. Rather gather related functions together in smaller groups each group in its own file (what actually is done in OO with classes).
Someone does it here with a simple example, MVC without OO: http://www.fluffycat.com/PHP-Design-Patterns/Non-OO-MVC/
Yep, that about sums up MVC... but it doesn't have to be object oriented... you just need to follow a few golden rules:
The controller receives and processes input, generates any data and puts it in the model.
The view takes data from the model and renders it.
The controller should not format data for view - it should have no knowledge of how/why/what the view wants (eg doesn't insert HTML in a text string since the output could be JSON)
The view should not look-up any data for itself - if it's not in the model then the controller failed in it's job (throw/report an error).
Beyond that you can do things however you want. You'd basically need a set of procedures to act as controllers - parsing $_REQUEST vars (more likely as GET/POST/COOKIE) performing any data lookup building + filling the model, and then another set of procedures that at as views - taking what's in the model and rendering it for the user. The model can be as simple as an associative array.
Absolutely. Use any combination of the following:
Use include files.
Use functions.
Separate your source files.
Divide sections of your code within source files.
Use code blocks (curly braces).
Separate PHP and/or HTML and/or JS files.
Anything that organizes your code more along the lines of Models, Views, and Controllers. It may not be "pure" or "correct" MVC in some people's minds...but if it organizes your procedural code more meaningfully or teaches you more about MVC, then it's a good thing.
This is kinda weird.
MVC is OO pattern and you want to approach it with a procedural context.
The first thing that comes to my mind is to have some kind of templating engine in order to split the PHP from the HTML code. This will be one big step towards procedural MVC :)
The next thing is to name functions of the same group (that means, functions that contains logic for related objects) with prefixes (like you group methods under a class name).
For example - look PHP procedural functions for working with mysql :
mysql_connect()
mysql_real_escape_string();
mysql_select_db();
mysql_query();
etc.
And group those functions in separate files. This will help to decouple a bit of the logic too.
If anything else come to my mind, i'll edit my post :)
If you are implementing a new design pattern you most likely are refactoring or writing something from scratch. I highly recommend moving to OOP if you plan to use MVC. It could be implemented procedurally but will be very hackish and not a good solution.
There are several free MVC php solutions that you can pick up easily. Here are a few:
Zend Framework
Kohana
Code Ignighter
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
So I've been looking up more tutorials and articles about the MVC design pattern to deepen my understanding of them and I'm starting to doubt if I have been doing it all wrong. So yeah the goal of those patterns are to make code reusable and to minimize repeated code, correct?
I've been seeing various ways of how those design patterns are explained which are confusing me a bit. In the past I thought it was the controller-as-a-mediator-between-model-and-view way, but now I'm learning that that was wrong and that the view is actually much more than just a template. Then I also read somewhere (I think here) that in a true MVC pattern, there is by definition only one model and all the other "models" are just different facets of the single model. Is this the case? Is this the best way to separate code and make it reusable? How would that look like in code? And again somewhere else I read that for web-applications it is better to stick to the MVVM pattern.
So now I'm a bit confused. What IS the most effective pattern to separate concerns in a web-application and make the code reusable? I would prefer to not only see a description of this pattern, but also a short example in code so I understand it better.
So yeah the goal of those patterns are to make code reusable and to minimize repeated code, correct?
Is this the best way to separate code and make it reusable?
Nope. It really isn't.
The goal in MVC and MVC-inspired patterns is to isolate business logic (model layer) from the user interface. And within the UI - to divide it into managing input and output.
Basically, MVC and MVC-inspired patterns are arcitectural design patterns that implement principle know as Separation of Concerns.
Then I also read somewhere (I think here) that in a true MVC pattern, there is by definition only one model and all the other "models" are just different facets of the single model. Is this the case?
No. Model is not a "thing" (class, object). It is a layer. Same way as you could say that all of controllers and views are contained in presentation layer or UI layer.
What people refer to as "models" are usually either domain objects or (much worse case) some form of active record implementation.
And again somewhere else I read that for web-applications it is better to stick to the MVVM pattern.
MVVM pattern add another layer between views and the model layer. It's best used for situations, when you either cannot controller the implementation of the views or/and the model layer.
Most of people confuse it with use of presentation object (M.Fowler has this nasty habit of adding "model" to everything, which create boundless confusions) concept. Presentation objects are meant to isolate reusable parts of UI logic.
How would that look like in code?
MVC and MVC-inspired patterns are created to manage large codebases. You apply MVC patter when simple use of object oriented practices are not enough to make code understandable. You do it by adding additional constraints to your codebase. MVC does not add anything new to your application. Instead it restricts where and what code can be written.
And "sort code example" will not actually illustrate the pattern. To actually understand, how it works, you should read something like PoEAA book .. or something similar.
What IS the most effective pattern to separate concerns in a web-application and make the code reusable?
It's a matter of opinion.
What IS the most effective pattern to separate concerns in a
web-application and make the code reusable?
There are no proven patterns for this. When you think of this you probably want to reduce code duplication (especially in Views) and make your code readable && maintable as much as possible.
It's a matter of data abstraction
In fact, by its definition, it directs you in the right way of thinking about things like that.
I would prefer to not only see a description of this pattern, but also
a short example in code so I understand it better.
First of all - Inheritance is the way to go, until it satisfies both, the Liskov Substitution Principle and the Single Responsibility Principle.
As mentioned above, there's no proven pattern for that, but there's a proven technique for that.
In PHP world, your MVC/MVVM application must implement at least:
PSR-0 Autoloader
Router + Dispatcher (kinda Front Controller)
Common things to keep in mind:
1. Model is an abstraction layer (in MVC/MVVM/MVP)
That consist of lots classes, that deal with application core logic.
If you call an object Model then you end up violating the Single-Responsibility Principle.
Wrong implementation:
Let's imagine for a moment, that model is a class,
Since in most cases we deal with forms, we basically want:
Forms to be valid
Insert/Update/.. a record if valid, then
So, a "model" for this would look like this:
$model = new RegisterForm(...);
if ($model->isFormValid($formData)) {
if ($model->insertRecord($formData)) {
echo 'Thanks for registration';
}
}
Which obviously breaks the SRP. And maybe the LSP if you inherit from.
Correct implementation:
Since model is a layer, then it should look like:
A folder structure of a model layer would be similar to
/User/Login
- FormValidator.php
- FormValidatorInterface.php
- RecordManager.php
And since then, the usage itself is:
$formValidator = new User_Login_FormValidator(...);
if ($formValidator->isValid(..form data..)) {
$recordManager = new User_Login_RecordManager($pdo);
if ($recordManager->insert(..form data..)) {
echo 'Logged in';
}
} else {
print_r($formValidator->getErrors());
}
Now let's break it down ,
When your models are layers:
You can take advantage over Dependency Injection, SOLID Principles, which is good for unit-testings.
Your code becomes easy to read and maintain
When your models are objects, like FooModel:
You're doing it wrong - you mixing a concept with an implementation
You end up violating both the SRP and the LSP
2. What is actually MVC?
As you know it consists of 3 components, but instead of a lecture on this, let's take a look
Model is an abstraction layer that contains core logic of an application
A view is a class that directly reads data from a Model and handles user presentation logic.
Say, if on a login page a user isn't logged in, (that info comes from a Model), you have to show en error, otherwise do a redirect - that's a handling of UI logic
A controller only (also known as Editor) assign variables to a model (that come from $_POST or $_GET, or to a view
And keep in mind, that data validation should never be done in controllers. You have to define it in a model, then call it from a view
And also note,
You should never echo/print anything from classes. Never! This should be done outside of the triad, like this,
$modelLayer = new ModelLayer(...);
$view = new View($modelLayer, $controller);
$controller = Controller($modelLayer);
$controller->indexAction($_POST[...])
echo $view->render(); // render() should `include()` and capture (via ob_* functions) a HTML template.
3. What is not MVC?
Here's a collection of wrong ideas, you should keep in mind as well, you will be encountering over and over again:
A model - its an $instance that implement some kind of ActiveRecord or ORM, or abstract table access.
A view is a dumb HTML template
A controller is a bridge between models and views, that collect information from a model then passes it to view. It also does data validation and show errors.
The "common workflow" as
<?php
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
$controller->indexAction();
4. How about MVVM?
Here's a good article for you, that explains it. Note, he names a class Model just for demonstration.
Going through open source code is the best way to learn
This question is one that would have a long answer and most probably cause debates since it seems you are asking for an opinion. The best answer in this case to the most "effective pattern" is the pattern that solves your problem.
"Your design should be specific to the problem at hand but also general enough to address future problems and requirements" - GoF (Design Patterns - Elements of reusable objects)
As you say, some say use MVVM (which I haven't heard off) and some of us use the MVC architecture. If you know both, use the one specific to your problem else use any that will work for you.
The best way to learn the MVC architecture and other patterns is not only through theory, but through coding. Take some of the code you have written and try to find where you used some of these patterns without knowing (eg. You might have used the Facade). How I learned and continue to learn is by going through open source code and trying to organise my code in a similar way.
If you are looking for a way to know where exactly to place a file, I don't think you find it. The best that you can do is have a rough idea of how files should be organized. To learn the MVC, download CodeIgniter and check out how the files are organized whilst having a look at their documentation. Also checkout other opensource code frameworks such cakePHP. Etc. I think this is the best way to get a clear understanding of it.
I think your problem is that you have been reading too much and not trying to implement some of the stuff you read.
As for code examples, I think you should google that as "short" is something it won't be. You need too see actual code and not examples. I'm sure you have seen enough examples by now from the tutorials you've been through.
Edit:
And notice I used "architecture" instead of "pattern", that's what I was taught. :) But I don't think it's a big deal though. #just-an-opinion
my question is about whether what I'm doing is proper , or if it causes security / performance issues.
Im using the $GLOBALS array , and filling it with a lot of values from the database, such as (page title, user information, template information ... etc) so that all my php files have access to this info. Im following the MVC design pattern, so this is how my View files have access to the information generated in the Model files.
If this is not the proper way to do things, please tell me why, and what is the proper way.
Thank you
You're is not following the MVC pattern, you are just using global variables to display something in a "shared all"-script in a "shared nothing"-architecture.
Doing output can mean you get a view of something, but normally that is not to be mixed with the term View of the MVC (Model-View-Controller) pattern. What you do, templating or output is maybe a better wording.
If this is not the proper way to do things, please tell me why, and what is the proper way.
If you want to implement MVC pattern, than this might be the MVC you're referring to:
Model: Your Filesystem and Database
View: Your HTML output + CSS + JS
Controller: Your PHP Script
MVC is just a pattern. You can implement it like you feel good. And you can find it in lot of stuff that has implemented nothing. It's just a pattern.
But more precisely the MVC pattern is more commonly seen for an object oriented implementation of it. Your implementation is totally different to such of a object oriented one, you're using global state instead of object instances.
But you have not written in your question that you thought about implementing an object oriented MVC pattern and that templating script you use is part of it.
It can be perfectly proper to do it like you do it depending on the needs to fulfil.
MVC is just a pattern. It has pro's and con's. It has benefits and it has consequences. It's just a pattern.
Especially if you're concerned about performance don't make things more complicated as they need to be, e.g. loading a full blown object tree to just display some variables inside a HTML template.
No, it's a very messy practice.
No, its got nothing to do with MVC.
A fundamental concept of modular programming (which underpins object-oriented programming and overlaps significantly with functional programming) is that global variables are bad - an awful lot of what constitutes good programming (and good programming languages) is all about isolating parts of the system from other parts.
That you are storing the data in global variables does nothing to help your objective of making the information available to all php files.
By all means group them under, say, a single global array, that way you don't have to keep passing it around in function/method calls.
One approach to populating maintaining the common data is to add implement processing of it withni a custom session handler.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 12 years ago.
Improve this question
The vast amount of frameworks available for PHP now use MVC. Even ASP.net has its own MVC module.
I can see the attraction of MVC, I really can and I use it frequently. The only downside that I can see is that you have to fire up the whole system to execute a page request. Depending on your task this can be a little wasteful.
So the question. In a professional environment is this the only way to use PHP nowadays or are their other design methods which have alternative benefits?
I don't like anyone telling me how to write a code. If I want to use MVC I will, if I find a better way that solves specific task, I will use it. I don't like when people turn MVC into a religion. I also think many php coders misunderstand the MVC concept and think they are using MVC pattern when in fact most of the times that are not using a 100% pure MVC. The truth is that it's not easy nor very efficient to write a website that is 100% MVC and is written in php.
Most people having most difficulties in the "V" part of the MVC. The "M" is easy. It's your data. If you storing your data in the database and have a database access class, that's your "M" part, you good with "M"
Now the controller: when user clicks on any link of your page, your php code must get the data from the "M" (database), prepare it, apply some logic like adding personalization to logged in user, adding "please login" link if user not logged it, etc. This is your "C" part.
The problem that most people are having with is separating the "V" View from "C" (controller) This is not easy nor is it the most efficient way to code in php. In many cases the controller part must already generate some html, so you blur the line between controller and view.
If you want to stay pure MVC then you must make sure that your controller returns a pure data, then the View class takes some template, plugs in your data and returns the HTML. This is where the problem lies in php. There is no easy and efficient way to do templating where a template just takes a pure data as input and returns the html. If there was an easy way, then there would not be reason for people to keep coming up with yet another new template library. The reason the there are so many templating libraries for php is because there are always programmers that are not happy with ANY of the existing ones and keep trying to invent their own, better one.
The only pure templating library in my opinion is the XSLT, which is fully supported by php, it's comes with php, it works, it's powerful, great templating engine, better yet, it's a standard, platform independant language. Once you learn XSLT you can use it in any other programming language like Java. But it does have one tiny problem, however. It requires the input to be an XML. Sure, you can create a great, 100% valid XML in php also using DOM library which is also part of php. The problem is that it will be slow. You will be doing double the work: first creating XML from your array of data, then trasforming that XML into HTML with your XSL template. This is why the approach of XSLT as templating engine never took off in php.
Now you left with the other options to parse templates, usually its regex based approach. You see how it always gets complicated when we get to the "V" part of the MVC?
The "M" is easy, the "C" is some type of pure php code, be it OOP or procedural code, does not matter. It's the "View" that is the tricky one.
So my advice is - don't worry too much about sticking to pure MVC. It's OK for a controller to spit out chunks of html here and there.
Well there are a lot of other approaches.
MVC is just popular because it suits most situations (or better said can be used in most situations) and has established itself as a de-facto standard.
What can be said is that every programming/design pattern - or more specific architectural - depends on some classification.
Those are often (of course they can be devided further):
User Interface (pretty images, forms etc)
Application (your application logic and stuff that needs to be secured from the client - ak lot of that can often be done in the user inteface, eg. by javascript)
Database - self explaining
Infrastructure (very basic stuff like hard disk, server systems, network etc.)
Of course there is always the naive, procedural straight-forward approach but also a lot fo other patterns that can link and structure the access and controlling to these basic layers.
Mvc is one of them. But here are some example of others:
http://en.wikipedia.org/wiki/Model_View_ViewModel
http://en.wikipedia.org/wiki/Model_View_Presenter
Is MVC-ARS preferable to classic MVC to prevent overloading?
And here a lot more:
http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)
I've been learning OOP programming for about a year and a half now and have developed a fairly standard framework to which I generally abide by. I'd love some feedback or input on how I might improve some functionality or if there are some things I'm overlooking.
VIEW MODE
1) Essentially everything starts at the Index.php page. The first thing I do is require my "packages.php" file that is basically a config file that imports all of the classes and function lists I'll be using.
2) I have no direct communication between my index.php file and my classes, what I've done is "pretty them up" with my viewfunctions.php file which is essentially just a conduit to the classes so that in my html I can write <?php get_title('page'); ?> instead of <?php echo $pageClass->get_title('page'); ?> Plus, I can run a couple small booleans and what not in the view function script that can better tailor the output of the class.
3) Any information brought in via the database is started from it's corresponding class that has direct communication with the database class, the only class that is allowed direct to communicate with the database (allowed in the sense that I run all of my queries with custom class code).
INPUT MODE
1) Any user input is sent to my userFunctions.php.
2) My security class is then instantiated where I send whatever user input that has been posted for verification and validation.
3) If the input passes my security check, I then pass it to my DB class for input into my Database.
php general model http://img139.imageshack.us/img139/3319/phpmodel.gif
FEEDBACK
I'm wondering if there are any glaringly obvious pitfalls to the general structure, or ways I can improve this.
Thank you in advance for your input. I know there is real no "right" answer for this, but I imagine a couple up votes would be in order for some strong advice regarding building frameworks.
-J
One thing I would recommend you do is to go ahead and separate your functions into classes. I understand the points you made about avoiding instantiations but consider this: any framework will, by necessity, begin to accumulate a large number of functions.
Instead of doing
<?php get_title('page'); ?>
you would be better served to create a Page class with all of its functions inside of said class which you call statically. Then, your code becomes
<?php Page::GetTitle('page'); ?>
a much more descriptive naming convention and will become critical later on when trying to avoid naming collisions (you only have to avoid name collisions on say, 50 classes, rather than two thousand functions).
I would study up on the Model-View-Controller design methodology (as ircmaxell hinted at in his post). A lot of very powerful and very well-written frameworks apply this principle, and not just PHP frameworks either. My suggestion - study Yii for how your application should be controlled - very slick and the creator makes excellent use of static variables to control class instantiation.
Good luck with your framework!
Well, the only issue that I can see (without seeing code), is that SQL will be everywhere. What I'd suggest is creating a "model" layer in front of the DB connection class. That way, all your sql is in one spot (break it off into multiple models, etc). It makes maintenance MUCH easier (if you want to add a column to a table, optimize a query, etc)...
Otherwise, it looks like a good start!
Nice presentation. I would definitely look under the hood at other popular frameworks for some insight.
At first glance, I would suggest to see if you can find a way to only load the classes you need per request. Loading them all for every request may become unfeasible if the class library grows large.
Are you using autoloaders? It seems that you will be using a lot of requires... maybe I am just misinterpreting. I think it is great that you are writing your own framework. I don't see it as "reinventing the wheel" either as you are writing it to accomplish the tasks you want to accomplish and can control the overall weight of your project as well as, since you are by most standards still moderately new to OOP, learning a ton I am sure from the experience. Creating your own frameworks, trying to improve other peoples code and learning how others do things and why is an amazing learning experience and in my opinion will drastically improve your programming skills and understanding.
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.