dpvmtdu364462 2013-10-01 19:10
浏览 92
已采纳

Laravel从REST API检索数据

Okay so I have a following situation:

The system I am building is retrieving data from a REST api and saving that data into a database. What I am wondering is how could this be implemented and where would behaviour like this go in sense of Laravels structure (controller, model etc.)? Does Laravel have a built in mechanism to retrieve data from external sources?

  • 写回答

5条回答 默认 最新

  • doubeng9567 2013-10-02 08:26
    关注

    First you have to make routes in your app/routes.php

    /*
        API Routes
    */
    
    Route::group(array('prefix' => 'api/v1', 'before' => 'auth.basic'), function()
    {
        Route::resource('pages', 'PagesController', array('only' => array('index', 'store', 'show', 'update', 'destroy')));
        Route::resource('users', 'UsersController');
    });
    

    Note: If you are not required authentication for API call, you can remove 'before' => 'auth.basic'

    Here you can access index, store, show, update and destroy methods from your PagesController.

    And the request urls will be,

    GET http://localhost/project/api/v1/pages // this will call index function
    POST http://localhost/project/api/v1/pages // this will call store function
    GET http://localhost/project/api/v1/pages/1 // this will call show method with 1 as arg
    PUT http://localhost/project/api/v1/pages/1 // this will call update with 1 as arg
    DELETE http://localhost/project/api/v1/pages/1 // this will call destroy with 1 as arg
    

    The command line CURL request will be like this (here the username and password are admin) and assumes that you have .htaccess file to remove index.php from url,

    curl --user admin:admin localhost/project/api/v1/pages    
    curl --user admin:admin -d 'title=sample&slug=abc' localhost/project/api/v1/pages
    curl --user admin:admin localhost/project/api/v1/pages/2
    curl -i -X PUT --user admin:admin -d 'title=Updated Title' localhost/project/api/v1/pages/2
    curl -i -X DELETE --user admin:admin localhost/project/api/v1/pages/1
    

    Next, you have two controllers named PagesController.php and UsersController.php in your app/controllers folder.

    The PagesController.php,

    <?php
    
    
    class PagesController extends BaseController {
    
    
        /**
         * Display a listing of the resource.
         *
         * @return Response
         * curl --user admin:admin localhost/project/api/v1/pages
         */
    
        public function index() {
    
            $pages = Page::all();;
    
            return Response::json(array(
                'status' => 'success',
                'pages' => $pages->toArray()),
                200
            );
        }
    
    
        /**
         * Store a newly created resource in storage.
         *
         * @return Response
         * curl --user admin:admin -d 'title=sample&slug=abc' localhost/project/api/v1/pages
         */
    
        public function store() {
    
            // add some validation also
            $input = Input::all();
    
            $page = new Page;
    
            if ( $input['title'] ) {
                $page->title =$input['title'];
            }
            if ( $input['slug'] ) {
                $page->slug =$input['slug'];
            }
    
            $page->save();
    
            return Response::json(array(
                'error' => false,
                'pages' => $page->toArray()),
                200
            );
        }
    
        /**
         * Display the specified resource.
         *
         * @param  int  $id
         * @return Response
         * curl --user admin:admin localhost/project/api/v1/pages/2
         */
    
        public function show($id) {
    
            $page = Page::where('id', $id)
                        ->take(1)
                        ->get();
    
            return Response::json(array(
                'status' => 'success',
                'pages' => $page->toArray()),
                200
            );
        }
    
    
        /**
         * Update the specified resource in storage.
         *
         * @param  int  $id
         * @return Response
         * curl -i -X PUT --user admin:admin -d 'title=Updated Title' localhost/project/api/v1/pages/2
         */
    
        public function update($id) {
    
            $input = Input::all();
    
            $page = Page::find($id);
    
            if ( $input['title'] ) {
                $page->title =$input['title'];
            }
            if ( $input['slug'] ) {
                $page->slug =$input['slug'];
            }
    
            $page->save();
    
            return Response::json(array(
                'error' => false,
                'message' => 'Page Updated'),
                200
            );
        }
    
        /**
         * Remove the specified resource from storage.
         *
         * @param  int  $id
         * @return Response
         * curl -i -X DELETE --user admin:admin localhost/project/api/v1/pages/1
         */
    
        public function destroy($id) {
            $page = Page::find($id);
    
            $page->delete();
    
            return Response::json(array(
                'error' => false,
                'message' => 'Page Deleted'),
                200
            );
        }
    
    }
    

    Then you have model named Page which will use table named pages.

    <?php
    
    class Page extends Eloquent {
    }
    

    You can use Laravel4 Generators to create these resources using php artisan generator command. Read here.

    So using this route grouping you can use the same application to make API request and as a front-end.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题