Problem
When it comes to interactive HTML5 and model binding, AngularJS is really powerful. PHP frameworks, on the other hand, such as Yii, allow for the building of rapid, well-structured, secure, and powerful web applications. Both systems offer powerful data access, iteration, and page layout capabilities.
Is mixing the two approaches (client-side and server-side “page setup”) a good or bad idea, or does it go against the spirit of interactive, seamless HTML5 AJAX online applications?
I’m not talking about producing JS with PHP (see this question); I’m talking about generating an AngularJS-based UI.
I also know that instead of collecting data directly from PHP variables, an AngularJS page should (or can) contact with the server via REST APIs to get data (see this question). However, it appears to me that designing the “frame” for the complete web site individually in PHP (for example, building the main menu or handling authorization/sessions, etc.) is more convenient.
Asked by Dani
Solution #1
It appears that you are more comfortable programming in PHP and have allowed this to prevent you from realising the full potential of web applications.
It is feasible for PHP to render partials and entire views, but I do not encourage it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be more user-friendly and easy to maintain.
I would advise you to become more comfortable thinking in an API-centric manner. Rather than having PHP output a pre-rendered view and relying on Angular for DOM modification, consider having the PHP backend emit the data that needs to be acted on RESTFully and then presenting it to Angular.
To render the view, we’ll use PHP:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How to handle the same problem using an API-centric approach with JSON output like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
You could do a get in Angular and handle the response on the client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
The technique you proposed blending client and server side may be appropriate for short projects when maintenance is not a concern and you are the sole author, but I prefer the API centric approach because it will provide a more accurate separation of concerns and will be easier to maintain.
Answered by Kenneth Lynne
Post is based on https://stackoverflow.com/questions/15623967/should-i-mix-angularjs-with-a-php-framework