Should I Mix Angularjs with a PHP Framework

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend 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 easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Should we use a php framework or build our own?

Don't develop your application for the future. Chances are in 3-4 years you're going to completely scrap this project anyways. And if you really do end up having 1 million+ active users you'll have a large cash flow (hopefully) to refactor at that point.

You're a start up, your best bet is to launch something ASAP and see if people even think your idea is worth while.

Too many companies die working out the small details. Get cash-flow positive and then start worrying about optimizing and refactoring the application when you can hire your own in-house developers.

Obviously you don't want to have awesome user-experience so that should be the only true goal early on.

To answer your question... what I've found is very simple to do is something like this:

Use an existing PHP framework if you're going the PHP route. Something like YII or Laravel because these are well documented and easy to get started on ASAP.

If you're building an API then use something simple that allows you to proliferate some sort of monolith very very quickly.

As for a front-end... it doesn't really matter. It can be done with angularJS or any other JS framework very easily. I prefer AngularJS just because it's what I've worked with but there are many other great options out there as well.

I'd just use whatever the dev team is most comfortable with for now and then when you redo the app (which will inevitably happen in a few years for a new company).

What application structure to use with AngularJS and Laravel?

There are two ways to combine these frameworks:

  1. Only client-side rendering

    This is the easier way and used by most web applications. In this case you would use Laravel as an API endpoint which will return JSON. Angular can query this data through its $http or $resource service and compile the templates, which you store in the public folder. Angular templates are just HTML with directives and some {{var}} statements. This way Angular does all the routing too.

  2. Server-side and client-side rendering

    This is the harder way where Laravel would do the routing and compile some templates on the server-side. You would use Angular only for some interactions on the site in a way you would use jQuery for example. The benefit of this approach is performance as users will get the full HTML the first time they visit your site. The disadvantage is that you may have to write some logic twice and can’t use some of Angular’s features.


AngularJS and PHP backend

You might want to consider this type of application as actually TWO applications.

The first is the backend, the API. You can use your PHP framework to build an API that will allow you to have data persistency, validation (business logic), etc... and forget about the front end for now, you are only building an API for the backend data.

The second part of the app is the AngularJS frontend. This includes all of the views and everything that the client sees. None of that is coming from the backend.

This allows you to use the backend API (the PHP bit) to act as the data store, with it's own validation for safety, while having the seamless user experience and basic client side validation from AngularJS.

Routing is AngularJS, as that is the actual frontend that the client is using.

Caching can be done (if needed) in the backend, your API.

Validation will happen in both the frontend and the backend, although they can be slightly different if need be.

Remember, you build the backend strictly as an API, without consideration for the frontend (as if there will be more than one app using it), so it will have it's own validation rules and logic.

Hope that helps.

Mixing AngularJS with Phalcon Framework

This does border on personal opinion, but here's how I see it:

  1. Your angularjs javascript code will need to be in the public folder (or symlinked) so it gets served, no way around that.
  2. To redirect you can use $this->response->redirect("http://example.com/my/ng/app", true); wherever you decide to put it

However I would say that redirecting is unnecessary. Why not put your angularjs template in the index.phtml of the view? All of your angular templates can be just phalcon views.

On a personal note, I started off doing a hybrid admin system part phalcon, part angularjs... and as I have gone on there is less and less phalcon in there; angularjs just makes a lot of it seem unnecessary. Now most of my pages start off getting their initial data from the controller to save an ajax request, and even having the templates served all in one go

<script type="text/javascript">
var myInitialData = <?=json_encode( $dataFromController )?>;
</script>

<script type="text/ng-template" id="myTemplate">
html for template ajax uses goes here
</script>

<div ng-controller="myController">
<!-- controller can access data with $window.myInitialData -->
html here
</div>

And then communicate with the phalcon controllers via json

Combining Angularjs and CodeIgniter

It sounds like you're looking to gradually make less use of CodeIgniter's (CI) routing as your angular application grows. This is not difficult but requires a lot of detail. Which method will work depends on your project structure. Note: I removed index.php from Code Igniter URLs, so the paths below may be different than default.

1) CodeIgniter installed in root

If CI is installed on the root of your server, you can create a folder within CI (for instance I have an "ng" folder). Your project will look like:

    /controllers
/models
/ng
(etc)
/index.php (code igniter index file)

place an .htaccess file within /ng with the following:

    Order allow, deny
Allow from all

This allows the files within /ng to be directly accessed, rather than sending those requests back through CI's routing system. For example you can load this directly now:
example.com/ng/partials/angular-view.html

The main web page will still be created by CodeIgniter, but it can now include Angular assets, such as partial views, etc. Eventually you can replace most of what CodeIgniter is doing by just returning a simple page, and having Angular load partial views from /ng like it's designed for.

This method is nice because CodeIgniter can control whether that initial page is loaded at all (via some user authentication code in your CI controller). If user isn't logged in, they are redirected and never see the Angular app.

2) CodeIgniter in Directory

If CI is installed in a directory, such as example.com/myapp/(code igniter) you can simply create a directory next to it, example.com/myappNg/

    /myapp/
/myapp/controllers/
/myapp/models/
/myapp/(etc)
/myapp/index.php (code igniter index file)
/myappNg/
/myappNg/partials/
/myappNg/js/
/myappNg/(etc)

Now in your Angular application, you can request resources from CI by making paths relative to the domain root, rather than relative to the Angular app. For instance, in Angular, you will no longer request a partial view from the Angular folder partials/angular-view.html, rather you'll want to request views from CI /myapp/someResource. Note the leading /. "someResource" can return an html document, or JSON or whatever you're doing with Code Igniter in the first place.

Eventually you can replace the number of paths which reference /myapp/. Once you no longer use CI for anything, you can simply place your Angular index.html in /myapp/ and it will continue to reference your paths at /myappNg/.

TL;DR Make your Angular app fully available and decouple it from CodeIgniter. Gradually move toward using Angular partial views and other JSON sources instead of linking to CodeIgniter pages. Eventually replace your CodeIgniter endpoint with an HTML file which bootstraps Angular.

Running PHP within angular

AngularJS is completely client side. You can put PHP in your HTML templates, but if you don't configure your webserver to parse HTML files as PHP then your PHP isn't even going to be parsed.

Even if it did, AngularJS caches these templates so it will only be 'run' on the server a single time. This means if the template in question is swapped out, then data changes on the server that the template makes use of and then it is swapped back in again, the updates to the data are not going to be reflected in the template because there's absolutely zero knowledge on Angular's side of these updates occurring.

A good idea like @Jonast92 says in his comment is to try not to mix client-side and server-side concerns and enforce a strict separation between them. Use Angular models in your angular application's templates. Instead of something like:

<p><?php echo $item->description; ?></p>

Use an angular model:

<p>{{ item.description }}</p>

If you need data from the server in order to do this, make an Angular service to go out and get it for you:

angular.module('app').controller('controller', [
'$scope', 'ItemManager',
function($scope, ItemManager) {
$scope.item = null;

ItemManager.getItem('item-id').then(
function(item) {
$scope.item = item;
}, function() {
console.log('load item failed');
}
);
}
]);

angular.module('app').service('ItemManager', [
'$http', '$q',
function($http, $q) {
var svc = {
getItem: getItem
};

return svc;

function getItem(id) {
var defer = $q.defer();
$http.get('/items/' + id)
.success(function(data) {
defer.resolve(data);
})
.error(function() {
defer.reject();
})
;

return defer.promise;
}
}
]);

AngularJS and Codeigniter - Combination & Data Transfer

Combination of CodeIgniter and AngularJS would help you to build new range of HTML5 Applications.

Unlike JQuery, AngularJS is a front-end framework, which depends on the data from backend, all communications from the front-end happen through a Controller Methods, there are operations for get and post in Angular.

CodeIgniter will act as an API which will output an json response to the Angular controller.

I believe json_encode(data) will output the required JSON string, which upon receipt by front-end, the data presentation layer of Angular takes care of the things /or if you'd like to perform any operation over the data, Angular can do that also.

I don't hold any links for this combination, because most people have shifted towards Ruby on Rails and AngularJS combination, fearing the stop of new release of CodeIgniter

Regret for not having any satisfactory links/blog post.
If time allows me to make a proof of concept, I would be very happy to post the link.

Hope this helps.

EDIT

JSON

    [
{"title": "t1"},
{"title": "t2"}
....
]

HTML

 <body ng-app="app">
<div ng-controller="MsgCtrl">
<ul>
<li ng-repeat="m in msg">{{m.title}}</li>
</ul>
</div>
</body>

JS

 var app = angular.module("app", []);

app.controller("MsgCtrl", function($scope, $http) {
$http.get('/index.php/ctrlname/methodname').
success(function(data, status, headers, config) {
$scope.msg = data;
}).
error(function(data, status, headers, config) {
// log error
});
});

UPDATE

For Insert, Delete, Update using CodeIgniter and AngularJS

CodeIgniter Controller

class Msg extends CI_Controller {

public function retrieveall() { .. } // Retrieves all Content from the DB
public function create(){ .. } // Inserts the given data to DB
public function retrieve($id){ .. } // Retrieves specific data from the DB
public function update($id, $title){ .. } // Updates specific data from the DB
public function delete($id){ .. } // Deletes specific data from the DB

...

}

CodeIgniter Routing

$route['m'] = "msg";
$route['m/(:any)'] = "msg/$1";

HTML

<body ng-app="app">
<div ng-controller="MsgCtrl">
<ul>
<li ng-repeat="m in msg">
{{m.title}}

<a href="#" ng-click="delete(m.id)">Delete</a>
<a href="#" ng-click="edit(m.id)">Edit</a>
</li>
</ul>

<input type="text ng-model="create.title">
<button type="submit" ng-click="formsubmit"> Submit </button>

<input type="text ng-model="editc.title">
<button type="submit" ng-click="editsubmit(editc.id)"> Submit </button>
</div>
</body>

JS

var app = angular.module("app", []);

app.controller("MsgCtrl", function($scope, $http) {
$http.get('/index.php/m/retrieveall').
success(function(data, status, headers, config) {
$scope.msg = data;
}).
error(function(data, status, headers, config) {
// log error
});

$scope.delete = function($id) {
$http.get('/index.php/m/delete/' + $id).
success(function(data, status, headers, config) {
$scope.result = data;
}

$scope.edit = function($id) {
$http.get('/index.php/m/retrieve/' + $id).
success(function(data, status, headers, config) {
$scope.editc = data;
}

$scope.editsubmit = function($id) {
$http.get('/index.php/m/update/' + $id +'/' + $scope.editc.title).
success(function(data, status, headers, config) {
$scope.result = data;
}
}

$scope.formsubmit = function($id) {
$http.post('/index.php/m/create', {data: create}).
success(function(data, status, headers, config) {
$scope.result = data;
}
}
});

I believe this would help you understand. It's a bare example

Any suggestion of server side frameworks to combine with angularjs

Try CakePhp, Laravel 4.2 and above, codeigniter



Related Topics



Leave a reply



Submit