質問

Maybe I'm doing this wrong alltogether. But I'm doing my first MVC in Laravel. Here is my setup.

The app is gonna download data from varoius sources and save to a database for output.

I have two controllers. One that saves data to the database and one that downloads data from instagram. In the Instagram-controller. I currently just output the data. I would like to save it using my save-controller instead.

Instagram controller:

class InstagramController extends BaseController {

public function read($q)
{
    $client_id = 'ea7bee895ef34ed08eacad639f515897';

    $uri = 'https://api.instagram.com/v1/tags/'.$q.'/media/recent?client_id='.$client_id;
    $response = $this->sendRequest($uri);
    print_r(json_decode($response));
    //return json_decode($response);
}

public function sendRequest($uri){
    $curl = curl_init($uri);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    $responses = curl_exec($curl);
    $responses = json_decode($responses);
    curl_close($curl);
    echo '<pre>';
    foreach ($responses->data as $data) {
        //0/{postid}/{url}/{author}/{content}
        $type = 0;
        $postid = $data->id;
        $url = $data->link;
        $author = $data->user->username;
        $content = $data->images->standard_resolution->url;


        echo $type.' '.$postid.' '.$url.' '.$author.' '.$content.'<br />';
    }
    //var_dump($responses->data);
    echo '</pre>';
    //return $response;
}

}

Save Controller:

class PostController extends BaseController {
public function save($type, $postid, $url, $author, $content)
{
    $post = new Post;
    $post->type = $type;
    $post->postid = $postid;
    $post->url = $url;
    $post->author = $author;
    $post->content = $content;
    try
    {
    $post->save();
    echo $post;
    }catch(Exception $e){
        throw new Exception( 'Already saved', 0, $e);
    }
   // 
}
}
役に立ちましたか?

解決

Controllers are mapped to actions (one route perform one action). You can call a controller by calling his route.

Because getting images, and saving them are part of the same action (ie: same route), I recommend you to move that code to a library or helper (or why not a model, because you are retrieving and saving data)

Anyway, I don't get the reason why you are doing that in controllers. Controllers usually perform operations between models and the views. Fetching data from a webservice belong more to models than to controllers. In fact, I really recommend you to move that code to a library to be reusable later. Your controller must only have the responsibility of calling the library's read method to read the image, then saving it locally using a model.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top