۶ میلیون تومن هدیه🎁 + کلی آفر جذاب در کمپین تابستون🔥 تابستون کوتاهه پس بزن بریم 👇
۰ ثانیه
۰ دقیقه
۰ ساعت
۱ پویا پارسایی
نحوه استفاده از سرویس FileService ؟
جامعه مهندسی نرم افزار ایجاد شده در ۱۹ فروردین ۱۴۰۲

سلام و عرض ادب

ما اومدیم FileServiceInterface رو پیاده سازی کردیم و به FileService هم گفتیم که این اینترفیس رو implement کنه:

:FileServicInterface

namespace Src\\Solid\\Lsp;
interface FileServiceInterface
{
    public function encode(EncodeableFileInterface $file);
}

:FileService

namespace Src\\Solid\\Lsp;
class FileService implements FileServiceInterface
{
    public function encode(EncodeableFileInterface $file)
    {
    }
}

پس میایم و توی providerمون این سرویس رو به اینترفیسش bind میکنیم:

namespace App\\Providers;
use Illuminate\\Support\\ServiceProvider;
use Src\\Solid\\Lsp\\FileService;
use Src\\Solid\\Lsp\\FileServiceInterface;
class FileServiceProvider extends ServiceProvider
{
    public $bindings = [
        FileServiceInterface::class => FileService::class
    ];
}

حالا میخوایم از این سرویس توی مثلا controller استفاده کنیم:

namespace App\\Http\\Controllers;
use Illuminate\\Http\\Request;
use Src\\Solid\\Lsp\\FileServiceInterface;
class FileController extends Controller
{
    public function download(FileServiceInterface $fileService)
    {
        return $fileService->encode();// inja chi bayad pass bedim?
    }
}

متد encode باید یه کلاس از نوع EncodeableFileInterface داشته باشه، ولی ما توی کلاس هامون هیچ جا EncodeableFileInterface رو implement نکردیم، یعنی در واقع هیچ کدوم از کلاس‌های concrete ما که شامل LocalFile, GoogleDriveFile و DropboxFile هستن، EncodeableFileInterface رو implement نکردن.

چجوری توی کنترلرمون یک آبجکت از نوع EncodeableFileInterface به متد encode پاس بدیم؟

حالا اگر که بخوایم بگیم که به طور مثال LocalFile بیاد علاوه بر FileInterface، اینترفیس EncodeableFileInterface رو هم implement کنه، پس باید متدهای این اینترفیس رو هم پیاده سازی کنه:

<?php
namespace Src\\Solid\\Lsp;
class LocalFile implements FileInterface, EncodeableFileInterface
{
    public function rename()
    {
        // TODO: Implement rename() method.
    }
    public function move()
    {
        // TODO: Implement move() method.
    }
    public function copy()
    {
        // TODO: Implement copy() method.
    }
    public function encode(EncodeableFileInterface $file)
    {
        // TODO: Implement encode() method.
    }
}

همونطوری که می‌بینید، متد encode به کلاس LocalFile اضافه میشه و ما باید یه فایل از نوع EncodeableFileInterface به این متد پاس بدیم، که به نظر کار درستی نمیاد.

ممنون میشم راهنمایی کنید

سلام خدمت شما. در این گزینه به نظرم بهترین روش این هست که EncodableFileInterface از خود FileInterface ارث بری کنه و اون مواردی که می‌تونن encode بشن از این Interface استفاده کنن. در جایی نیاز به encode داشتیم از EncodeableFileInterface و هر جا خود File ساده رو میخواستیم از FileInterface استفاده می‌کنیم.

بهترین پاسخ
کیوان علی محمدی ۲۵ فروردین ۱۴۰۲، ۰۹:۴۱