在laravel 4刀片视图上显示API xml数据

时间:2013-07-11 05:00:59

标签: laravel laravel-4 amazon-product-api blade

我正在开发一个网站,您可以在其中搜索亚马逊产品广告API的商品。 我在views / layouts / master.blade.php上有一个搜索框,其中包含以下代码:

    {{ Form::open(array('url' => 'AmazonAPI/api.php', 'method' => 'GET')) }}
        {{ Form::text('itemsearch', 'Search ...', ) }}
    {{ Form::submit('Search') }}

表单使用以下代码发布到api文件:

    <?php
        if(isset($_GET['booksearch'])) {
            /* Example usage of the Amazon Product Advertising API */
            include("amazon_api_class.php");

            $obj = new AmazonProductAPI();
            $result ='' ;
            try
            {
                $result = $obj->searchProducts($_GET['booksearch'],
                                               AmazonProductAPI::DVD,
                                               "TITLE");
            }
            catch(Exception $e)
            {
                echo $e->getMessage();
            }

            print_r($result->Items);


    ?>

搜索后,您将导航到该文件,并显示来自amazon的有效xml数据。但正如您所看到的,api文件是我的public / assets / AmazonAPI文件夹中的php文件,因此在设置xml样式时我无法扩展我的布局。 请告诉我如何将我的API代码包含在views / searching / index.blade.php刀片视图中,以便我可以在其上扩展布局,如:

@extends('layouts.mylayout')

@section('content')
//the api code goes here
@stop

另请告诉我打开表单的正确方法。

1 个答案:

答案 0 :(得分:1)

我将以简单且更Laravel的方式指导您完成此操作。 因此,您可以在libraries目录下创建文件夹app 并将您的amazon api文件放在libraries文件夹中。

现在在composer.json添加"app/your_amozon_api_library_folder_name"的类图中,类似于

"autoload": { 
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/your_amozon_api_library_folder_name",

现在使用composer dump-autoload or php composer.phar dump-autoload转储您的自动加载 现在你将amozon api加载到全球使用。

假设你有一个带有搜索方法的HomeController,现在把api代码放在搜索方法中,

public function search(){
  if(isset($_GET['booksearch'])) {
        /* Example usage of the Amazon Product Advertising API */
        //include("amazon_api_class.php"); no need to include

        $obj = new AmazonProductAPI();
        $result ='' ;
        try
        {
            $result = $obj->searchProducts($_GET['booksearch'],
                                           AmazonProductAPI::DVD,
                                           "TITLE");
        }
        catch(Exception $e)
        {
            echo $e->getMessage();
        }

        //print_r($result->Items);
        return View::make('your view name')->with('items',$result->Items);
 }
}