简体   繁体   中英

Repository pattern in Laravel. Method from model

Before I used repository pattern I can call method getImage() on my object model

class Product extends Eloquent{
    public funtion getImage(){
        //some query to database
    }
}

So, if I pass object of this class to view I can use simple in my view:

<img src="{{$product->getImage()}}"

But, now I implement RepositoryPatter, so I moved getImage() to ProductRepository

class ProductRepository{
    public function getImage(){
        //some query to database
    }
}

So, what I should do if I want still use $product->getImage(); in my view

I thought of several ways to solve this depending on what data do your repositories return and how you need this method to be used.

1) if you need a product or a list of products and you need all of them to get the images you can define a new method in your repos:

getProductsWithImages()
{
    //here you retrieve the needed products (that you already do) and retrieve and assign the images
}

So you could simply do this in your template:

<img src="{{ $product->image }}" ...

2) your repository might return objects of your own class (ProductEntity or something like that) and it can have a "getImage" method.

This way your current template should work as is.

3) you can have another "helper" class or service which would get the needed image:

<img src="{{ ProductHelper::getImage($image) }}" ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM