getherbert / herbert

The WordPress Plugin Framework:
http://getherbert.com/
632 stars 94 forks source link

Using $http not defined #59

Closed csrui closed 9 years ago

csrui commented 9 years ago

How is the $http available in this example?

When I try I get Notice: Undefined variable: http in ...

<?php namespace MyPlugin\Controllers;

use Herbert\Framework\Models\Post;
use Herbert\Framework\Http;

class PostController {

    /**
     * Show the post for the given id.
     */
    public function showPost($id, Http $http)
    {
        $post = Post::find($id);

        if(!$post)
        {
            return response('Post not found', 404);
        }

        if($http->has('json'))
        {
            return json_response($post);
        }

        return view('@MyPlugin/post/single.twig', ['post' => $post]);
    }
}
jasonagnew commented 9 years ago

It might be worth posting your original code incase I can spot something. If the example shown is called by route or panel then Http $http is injected for you. But if you decided to call that method like:

(new PostController)->showPost($id);

It wouldn’t work, and need to pass the $http to it. At any point you can get framework components by calling herbert('component') So you have two options:

(new PostController)->showPost($id, herbert('http'));

Or

 public function showPost($id)
    {
        $http = herbert('http');
        $post = Post::find($id);

        if(!$post)
                    ….
csrui commented 9 years ago

I have only this route:

$router->post([
    'uri'  => '/sc/cart',
    'uses' => __NAMESPACE__ . '\Controllers\CartController@add'
]);

and then this controller

<?php namespace ShirtCreator\Controllers;

use ShirtCreator\Models\Shirt;
use Herbert\Framework\Http;

class CartController {

    public function index()
    {

        header('Content-Type: application/json');
        return json_encode();

    }

    public function add() {

        // $http->get('shirt_id');
        $shirt = Shirt::whereId($_POST['shirt_id'])->first();
jasonagnew commented 9 years ago

You've forgot to add Http $http in the parameters of the function:

public function add() {}

Should be:

public function add(Http $http) {}
csrui commented 9 years ago

thank you