dimanche 19 juillet 2020

Laravel 5.8 dependecy injection - how to inject model to service

I have BooksService class which should be injected by Book model object. Then I want to inject BooksService to BookController. But I dont know ho to do it.

I am getting an error Class App\Model\BookService does not exist. Is it neccesary to register it somewhere? Also I am not sure if I am doing it right. Is it in this code?

BookService

namespace App\Model;

class BookService
{
    /** @var  Book */
    public $books;


    // I am not sure if this is ok
    public function construct(Book $books)
    {
        $this->books = $books;
    }


    public function test()
    {
        dd($this->books);
    }

}

BookController

namespace App\Http\Controllers;

use App\Http\Requests\StoreBook;
use App\Model\Book;
use App\Model\BookService;
use Illuminate\Http\Request;


class BookController extends Controller
{

    ....    

    // This throws me an error BookService does not exists
    public function create(BookService $bookService)  
    {
        $bookService->test();
        return view('book.create');
    }

    ....
}


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire