本文共 24255 字,大约阅读时间需要 80 分钟。
angular单页应用
Laravel and Angular have both become very well renowned tools in the web development world lately. Laravel for the great things it brings to the PHP community and Angular for the amazing frontend tools and its simplicity. Combining these two great frameworks only seems like the logical next step.
Laravel和Angular最近都已成为Web开发界非常知名的工具。 Laravel带来了PHP社区带来的伟大成就,而Angular带来了惊人的前端工具及其简单性。 将这两个伟大的框架结合起来似乎是合乎逻辑的下一步。
For our use cases, we will be using Laravel as the RESTful API backend and Angular as the frontend to create a very simple single page comment application.
对于我们的用例,我们将使用Laravel作为RESTful API后端,并使用Angular作为前端来创建一个非常简单的单页注释应用程序。
This will be a simple example to show off how to get started using these two technologies so don't hope for any extra database stuff on how to handle sub-comments or anything like that.
这将是一个简单的示例,以展示如何开始使用这两种技术,因此不要希望任何其他有关如何处理子注释或类似内容的数据库资料。
This will be a simple single page comment application:
这将是一个简单的单页注释应用程序:
Overall, these are very simple concepts. Our focus will be to see the intricacies of how Laravel and Angular can work together.
总体而言,这些是非常简单的概念。 我们的重点将是了解Laravel和Angular如何协同工作的复杂性 。
Go ahead and get your Laravel setup ready. We'll be doing some basic things to get our backend to do CRUD on comments:
继续,准备好您的Laravel设置。 我们将做一些基本的事情来使后端对评论进行CRUD:
We will need a simple structure for our comments. We just need text and author. Let's create our Laravel migration to create our comments.
我们将需要一个简单的结构来发表评论。 我们只需要文本和作者 。 让我们创建Laravel迁移以创建我们的注释。
Let's run the artisan command that will create our comments migration so that we can create the table in our database:
让我们运行artisan命令来创建注释迁移,以便我们可以在数据库中创建表:
php artisan migrate:make create_comments_table --create=comments
php artisan migrate:make create_comments_table --create=comments
We'll use the to create the text and author fields that we need. Laravel will also create the id column and the timestamps so that we know how long ago the comment was made. Here is the code for the comments table:
我们将使用创建所需的text和author字段。 Laravel还将创建id列和时间戳,以便我们知道多久之前进行评论。 这是注释表的代码:
// app/database/migrations/####_##_##_######_create_comments_table.php... /** * Run the migrations. * * @return void */ public function up() { Schema::create('comments', function(Blueprint $table) { $table->increments('id'); $table->string('text'); $table->string('author'); $table->timestamps(); }); }...
Make sure you go adjust your database settings in app/config/database.php
with the right credentials. Now we will run the migration so that we create this table with the columns that we need:
确保使用正确的凭据在app/config/database.php
调整数据库设置 。 现在,我们将运行迁移,以便我们使用所需的列创建该表:
php artisan migrate
php artisan migrate
With our table made, let's create an Eloquent model so that we can interact with it.
制作完表格后,让我们创建一个Eloquent模型,以便我们可以与其进行交互。
We will be using models to interact with our database. This will be very easy to do. Let's create a model: app/models/Comment.php
.
我们将使用模型与我们的数据库进行交互。 这将非常容易做到。 让我们创建一个模型: app/models/Comment.php
。
We now have our new table and model. Let's fill it with some sample data using .
现在,我们有了新的表格和模型。 让我们使用填充一些示例数据。
We will need a few comments so that we can test a few things. Let's create a seed file and fill our database with 3 sample comments.
我们将需要一些评论,以便我们可以测试一些东西。 让我们创建一个种子文件,并用3个示例注释填充我们的数据库。
Create a file: app/database/seeds/CommentTableSeeder.php
and fill it with this code.
创建一个文件: app/database/seeds/CommentTableSeeder.php
,并使用以下代码填充它。
delete(); Comment::create(array( 'author' => 'Chris Sevilleja', 'text' => 'Look I am a test comment.' )); Comment::create(array( 'author' => 'Nick Cerminara', 'text' => 'This is going to be super crazy.' )); Comment::create(array( 'author' => 'Holly Lloyd', 'text' => 'I am a master of Laravel and Angular.' )); } }
To call this Seeder file, let's open app/database/seeds/DatabaseSeeder.php
and add the following:
要调用此Seeder文件,请打开app/database/seeds/DatabaseSeeder.php
并添加以下内容:
// app/database/seeds/DatabaseSeeder.php... /** * Run the database seeds. * * @return void */ public function run() { Eloquent::unguard(); $this->call('CommentTableSeeder'); $this->command->info('Comment table seeded.'); }...
Now let's run our seeders using artisan.
现在,让我们使用工匠来运行播种机。
php artisan db:seed
php artisan db:seed
Now we have a database with a comment table, an Eloquent model, and samples in our database. Not bad for a day's work... but we're not even close to done yet.
现在,我们有了一个带有注释表的数据库 , 一个Eloquent模型和数据库中的示例 。 对于一天的工作来说还不错……但是我们还没有完成。
We will use to handle our API functions for comments. Since we'll be using Angular to display a resource and show create and update forms, we'll create a resource controller with artisan without the create or edit functions.
我们将使用来处理我们的API函数以进行注释。 由于我们将使用Angular来显示资源并显示创建和更新表单,因此我们将使用手Craft.io者创建资源控制器,而无需创建或编辑功能。
Let's create our controller using artisan.
让我们使用工匠创建我们的控制器。
php artisan controller:make CommentController --only=index,store,destroy
php artisan controller:make CommentController --only=index,store,destroy
For our demo app, we'll only be using these three functions in our resource controller. To expand on this you'd want to include all the functions like update, show, update for a more fully fledged app.
对于我们的演示应用程序,我们将仅在资源控制器中使用这三个功能。 要对此进行扩展,您需要包括所有功能,如update , show , update ,以提供更为完善的应用程序。
Now we've created our controller. We don't need the create
and edit
functions because Angular will be handling showing those forms, not Laravel. Laravel is just responsible for sending data back to our frontend. We also took out the update
function for this demo just because we want to keep things simple. We'll handle creating, showing, and deleting comments.
现在,我们创建了控制器。 我们不需要create
和edit
功能,因为Angular将处理显示这些形式的内容,而不是Laravel。 Laravel只是负责将数据发送回我们的前端。 我们只是为了保持简单而删除了此演示的update
功能。 我们将处理创建,显示和删除评论。
To send data back, we will want to send all our data back as JSON. Let's go through our newly created controller and fill out our functions accordingly.
要发送回数据,我们将希望将所有数据作为JSON发送回。 让我们浏览一下我们新创建的控制器,并相应地填写我们的功能。
Input::get('author'), 'text' => Input::get('text') )); return Response::json(array('success' => true)); } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { Comment::destroy($id); return Response::json(array('success' => true)); }}
You can see how easy it is to handle CRUD with Laravel and Eloquent. It's incredibly simple to handle all the functions that we need.
您可以看到使用Laravel和Eloquent处理CRUD有多么容易。 处理我们需要的所有功能非常简单。
With our controller ready to go, the last thing we need to do for our backend is routing.
准备好控制器后,我们后端需要做的最后一件事就是路由。
Extra Reading:
附加阅读 :
With our database ready to rock and roll, let's handle the routes of our Laravel application. We will need routes to send users to the Angular frontend since that will have its own routing. We will also need routes for our backend API so people can access our comment data.
在数据库准备就绪后,让我们处理Laravel应用程序的路由。 我们将需要路由来将用户发送到Angular前端,因为它将具有自己的路由。 我们还将需要后端API的路由,以便人们可以访问我们的评论数据。
Let's create the Angular pointing routes. We will need one for the home page and a catch-all route to send users to Angular. This ensures that any way a user accesses our site, they will be routed to the Angular frontend.
让我们创建角度指向路线。 我们将需要一个主页页面和一条通向所有人的路线,以将用户发送到Angular 。 这样可以确保用户以任何方式访问我们的网站,都将被路由到Angular前端。
We'll be prefixing our API routes with... (drumroll please)... api
. This way, if somebody wants to get all comments, they will use the URL: http://example.com/api/comments
. This just makes sense moving forward and is some basic API creation good tactics.
我们将在API路由的前面加上...(请鼓动)... api
。 这样,如果有人想获得所有评论 ,他们将使用URL: http://example.com/api/comments
: http://example.com/api/comments
。 向前迈进是有意义的,并且是一些基本的API创建良好策略。
'api'), function() { // since we will be using this just for CRUD, we won't need create and edit // Angular will handle both of those forms // this ensures that a user can't access api/create or api/edit when there's nothing there Route::resource('comments', 'CommentController', array('only' => array('index', 'store', 'destroy')));});// CATCH ALL ROUTE ============================= // all routes that are not home or api will be redirected to the frontend // this allows angular to route them App::missing(function($exception) { return View::make('index'); });
We now have our routes to handle the 3 main things our Laravel backend needs to do.
现在,我们有路线来处理Laravel后端需要做的三件事。
Testing All Our Routes Let's make sure we have all the routes we need. We'll use artisan and see all our routes:
测试我们的所有路线确保我们拥有所需的所有路线。 我们将使用工匠,并查看所有路线:
php artisan routes
php artisan routes
This command will let us see our routes and sort of a top-down view of our application.
该命令将让我们看到我们的路线以及我们应用程序的自顶向下视图。
We can see the HTTP verb and the route used to get all comments, get a single comment, create a comment, and destroy a comment. On top of those API routes, we can also see how a user get routed to our Angular application by the home page route.
我们可以看到HTTP动词和用于获取所有注释,获取单个注释,创建注释以及销毁注释的路由。 在这些API路由的顶部,我们还可以看到如何通过主页路由将用户路由到我们的Angular应用程序。
Finally! Our Laravel API backend is done. We have done so much and yet, there's still so much to do. We have set up our database and seeded it, created our models and controllers, and created our routes. Let's move onto the frontend Angular work.
最后! 我们的Laravel API后端已完成。 我们已经做了很多事情,但是,还有很多事情要做。 我们已经建立了数据库并将其作为种子 , 创建了模型和控制器 ,并创建了路线 。 让我们继续进行前端Angular工作。
I've seen this question asked a lot. Where exactly should I be putting Angular files and how does Laravel and Angular work together. We did an article on getting . This article works under the assumption that we aren't even going to use Blade.
我看到这个问题问了很多。 我应该将Angular文件放在哪里以及Laravel和Angular如何一起工作。 我们写了一篇文章,介绍如何使 。 本文是在我们甚至不打算使用Blade的前提下工作的。
To let Angular handle the frontend, we will need Laravel to pass our user to our index.php
file. We can place this in a few different places. By default, when you use:
为了让Angular处理前端,我们需要Laravel将用户传递到我们的index.php
文件。 我们可以将其放置在几个不同的地方。 默认情况下,使用时:
// app/routes.phpRoute::get('/', function() { return View::make('index'); });
This will return app/views/index.php
. Laravel will by default look in the app/views
folder.
这将返回app/views/index.php
。 Laravel默认情况下会在app/views
文件夹中查找。
Some people may want to keep Angular files completely separate from Laravel files. They will want their entire application to be housed inside of the public
folder. To do this is simple: just change the default View location to the public folder. This can be done in the app/config/view.php
file.
某些人可能希望将Angular文件与Laravel文件完全分开。 他们希望将整个应用程序放在public
文件夹中。 要做到这一点很简单:只需将默认的“查看”位置更改为公用文件夹。 这可以在app/config/view.php
文件中完成。
// app/config/view.php... // make laravel look in public/views for view files 'paths' => array(__DIR__.'/../../public/views'),...
Now return View::make('index')
will look for public/views/index.php
. It is all preference on how you'd like to structure your app. Some people see it as a benefit to have the entire Angular application in the public folder so that it is easier to handle routing and if it is needed in the future, to completely separate the backend RESTful API and the Angular frontend.
现在return View::make('index')
将寻找public/views/index.php
。 完全取决于您希望如何构建应用程序。 有人认为将整个Angular应用程序放在公用文件夹中是有好处的,这样可以更轻松地处理路由,并且如果将来需要,可以将后端RESTful API和Angular前端完全分开。
For Angular routing, then your partial files will be placed in the public folder, but that's out of the scope of this article. For more information on that kind of single page Angular routing, check out .
对于Angular路由,您的部分文件将放置在公用文件夹中,但这不在本文的讨论范围之内。 有关这种单页Angular路由的更多信息,请查看《 。
Let's assume we left everything default and our main view file is in our app/views
folder and move forward.
假设我们将所有内容保留为默认值,并且主视图文件位于app/views
文件夹中并继续前进。
index.php
) in this case. This is why we use a Laravel index.php
)时,才会发生Angular路由。 这就是为什么我们使用Laravel包罗万象 catch-all route. Laravel will handle the API routes and anything it doesn't know how to route will be sent to Angular. You can then set up all the routing for your Angular application to handle showing different views. 的路线。 Laravel将处理API路由,所有不知道如何路由的信息都将发送到Angular。 然后,您可以为Angular应用程序设置所有路由,以处理显示不同的视图。 Everything for our Angular application will be handled in the public
folder. This let's us keep a good separation of the backend in the app
folder.
我们的角应用一切都将在处理public
文件夹。 这让我们在app
文件夹中保持后端的良好隔离。
Let's look at the application structure we will have in our public
folder. We've created our Angular application to be modular since that is best practices. Now our separated parts of our application will be easy to test and work with.
让我们看一下public
文件夹中的应用程序结构。 因为这是最佳实践,所以我们已经将Angular应用程序创建为模块化的。 现在,我们应用程序的各个部分将易于测试和使用。
- public/ ----- js/ ---------- controllers/ // where we will put our angular controllers --------------- mainCtrl.js ---------- services/ // angular services--------------- commentService.js ---------- app.js
Our Angular service is going to be the primary place where we will have our HTTP calls to the Laravel API. It is pretty straightforward and we use the service.
我们的Angular服务将成为我们对Laravel API进行HTTP调用的主要场所。 这非常简单,我们使用服务。
// public/js/services/commentService.jsangular.module('commentService', []).factory('Comment', function($http) { return { // get all the comments get : function() { return $http.get('/api/comments'); }, // save a comment (pass in comment data) save : function(commentData) { return $http({ method: 'POST', url: '/api/comments', headers: { 'Content-Type' : 'application/x-www-form-urlencoded' }, data: $.param(commentData) }); }, // destroy a comment destroy : function(id) { return $http.delete('/api/comments/' + id); } }});
This is our Angular service with 3 different functions. These are the only functions we need since they will correspond to the api routes we made in our Laravel routes.
这是我们的Angular服务,具有3种不同的功能。 这些是我们唯一需要的功能,因为它们将与我们在Laravel路线中创建的api路线相对应。
We will be returning the promise object from our service. These will be dealt with in our controllers. The naming convention here also stays the same as the Laravel controller that we have.
我们将从我们的服务中返回Promise对象。 这些将在我们的控制器中处理。 这里的命名约定也与我们拥有的Laravel控制器相同。
With our Angular Service done, let's go into our controller and use it.
完成Angular Service之后,让我们进入控制器并使用它。
The controller is where we will have most of the functionality for our application. This is where we will create functions to handle the submit forms and deleting on our view.
控制器是我们拥有应用程序大部分功能的地方。 在这里,我们将创建用于处理提交表单和在视图上删除的函数。
// public/js/controllers/mainCtrl.jsangular.module('mainCtrl', [])// inject the Comment service into our controller.controller('mainController', function($scope, $http, Comment) { // object to hold all the data for the new comment form $scope.commentData = {}; // loading variable to show the spinning loading icon $scope.loading = true; // get all the comments first and bind it to the $scope.comments object // use the function we created in our service // GET ALL COMMENTS ============== Comment.get() .success(function(data) { $scope.comments = data; $scope.loading = false; }); // function to handle submitting the form // SAVE A COMMENT ================ $scope.submitComment = function() { $scope.loading = true; // save the comment. pass in comment data from the form // use the function we created in our service Comment.save($scope.commentData) .success(function(data) { // if successful, we'll need to refresh the comment list Comment.get() .success(function(getData) { $scope.comments = getData; $scope.loading = false; }); }) .error(function(data) { console.log(data); }); }; // function to handle deleting a comment // DELETE A COMMENT ==================================================== $scope.deleteComment = function(id) { $scope.loading = true; // use the function we created in our service Comment.destroy(id) .success(function(data) { // if successful, we'll need to refresh the comment list Comment.get() .success(function(getData) { $scope.comments = getData; $scope.loading = false; }); }); };});
As you can see in our controller, we have injected our Comment
service and use it for the main functions: get
, save
, and delete
. Using a service like this helps to not pollute our controller with $http
gets and puts.
如您在控制器中所见,我们注入了Comment
服务,并将其用于主要功能: get
, save
和delete
。 使用这样的服务有助于避免用$http
gets和puts污染我们的控制器。
On the Angular side of things, we have created our service and our controller. Now let's link everything together so that we can apply it to our application using ng-app
and ng-controller
.
在事物的角度方面,我们创建了服务和控制器 。 现在,将所有内容链接在一起,以便可以使用ng-app
和ng-controller
将其应用于我们的应用程序。
This will be the code to create our Angular application. We will inject the service and controller into. This is best practices since it keeps our application modular and each different part can be testable and extendable.
这将是创建Angular应用程序的代码。 我们将注入服务和控制器。 这是最佳实践,因为它使我们的应用程序保持模块化,并且每个不同的部分都可以测试和扩展。
// public/js/app.jsvar commentApp = angular.module('commentApp', ['mainCtrl', 'commentService']);
That's it! Not much to it. Now we'll actually get to our view where we can see how all these Angular parts work together.
而已! 没什么。 现在,我们实际上进入视图,可以看到所有这些Angular零件如何协同工作。
So far, after everything we've done up to this point, we still won't be able to see anything in our browser. We will need to define our view file since Laravel in our home route and our catch-all route returns return View::make('index');
.
到目前为止,在完成所有操作之后,我们仍然无法在浏览器中看到任何内容。 由于Laravel在我们的本地路线中,我们将需要定义我们的视图文件,而我们的全部路线返回return View::make('index');
。
Let's go ahead and create that view now. We will be using all the Angular parts that we've created. The main parts that we've created from Angular that we'll use in index.php
are:
让我们继续创建该视图。 我们将使用我们创建的所有Angular零件。 我们将在index.php
中使用的从Angular创建的主要部分是:
body
tag ng-app和ng-controller :我们会将它们附加到我们的body
标签上,将它们应用到我们的应用中 ng-submit
SubmitComment() :我们将使用ng-submit
将此功能附加到表单中 loading
. If it is set to true, we'll show a loading icon and hide the comments 加载图标 :我们将创建一个名为loading
的变量。 如果设置为true,我们将显示一个加载图标并隐藏评论 Now let's get to the actual code for our view. We'll comment out the main important parts so we can see how everything works together.
现在,让我们进入视图的实际代码。 我们将注释掉主要的重要部分,以便我们可以看到一切如何协同工作。
Laravel and Angular Comment System Laravel and Angular Single Page Application
Commenting System
Now we finally have our view that brings all of the parts we created together. You can go ahead and play around with the application. All the parts should fit together nicely and creating and deleting comments should be done without a page refresh.
现在,我们终于有了将我们创建的所有部分整合在一起的观点。 您可以继续使用该应用程序。 所有部分都应该很好地配合在一起,并且无需刷新页面就可以创建和删除注释。
Make sure you take a look at the to test the application. Here are some quick instructions to get you going.
确保查看以测试应用程序。 以下是一些快速说明,可助您一臂之力。
git clone git@github.com:scotch-io/laravel-angular-comment-app
克隆git clone git@github.com:scotch-io/laravel-angular-comment-app
: git clone git@github.com:scotch-io/laravel-angular-comment-app
composer install --prefer-dist
安装Laravel: composer install --prefer-dist
app/config/database.php
在app/config/database.php
更改数据库设置 php artisan migrate
迁移数据库: php artisan migrate
php artisan db:seed
种子数据库: php artisan db:seed
Hopefully this tutorial gives a good overview of how to start an application using Laravel and Angular. You can bring this farther and create a full application that can handle multiple API calls on the Laravel side, and even create your own for multiple pages.
希望本教程能够很好地概述如何使用Laravel和Angular启动应用程序。 您可以更进一步,创建一个完整的应用程序,该应用程序可以处理Laravel端的多个API调用,甚至可以为多个页面创建自己的 。
Sound off in the comments if you have any questions or would like to see a specific use case. We can also expand on this demo and start adding different things like editing a comment, user profiles, whatever.
如果您有任何疑问或想查看特定的用例,请在评论中忽略。 我们还可以扩展此演示并开始添加其他内容,例如编辑评论,用户个人资料等等。
翻译自:
angular单页应用
转载地址:http://fnywd.baihongyu.com/
Comment #{ { comment.id }} by { { comment.author }}
{
{ comment.text }}Delete