php Laravel服务类,来自Controller的重构逻辑

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php Laravel服务类,来自Controller的重构逻辑相关的知识,希望对你有一定的参考价值。

<?php 

// 1) create a service class in:  App/Services/DeleteEventService.php
<?php
namespace App\Services ;

use App\Registration;
use App\Mail\DeleteEvent;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Controller;

class DeleteEventService extends Controller {

    public function __construct()
    {

    }

    public function deleteEvent($event) {
        $emails = [] ;

        // get all registrations from this event date
        $registrations = Registration::where( 'event_date', $event->event_date )->get() ;

        // get all user emails registered to this event date
        foreach( $registrations as $reg)
            $emails[] = $reg->user->email;

        // delete all entries from 'registrations' table that match this event
        Registration::where('event_date', $event->event_date )->delete() ;
        // delete the event
        $event->delete() ;

        // Mail admin and CC users that this event was deleted
        Mail::to( 'juan@c-istudios.com' )
            ->cc($emails)
            ->send( new DeleteEvent( 'Cancelled Event', $event->event_date ) );
    }

}


// 2) import these classes into our controller:
use App\Services\DeleteEventService;



// 2) Inject this service class into our method where it needs to be refactored
    public function destroy(DeleteEventService $evtServ, $id) {
        // find this event
        $emails = [] ;
        $event = Event::find($id) ;

        // using Service class:
        $evtServ->deleteEvent($event) ;

/*      // ^^ Refactored to Service Class DeleteEventService loaded via dependency injection ^^
        // get all registrations from this event date
        $registrations = Registration::where( 'event_date', $event->event_date )->get() ;

        // get all user emails registered to this event date
        foreach( $registrations as $reg)
            $emails[] = $reg->user->email;

        // delete all entries from 'registrations' table that match this event
        Registration::where('event_date', $event->event_date )->delete() ;
        // delete the event
        $event->delete() ;

        // Mail admin and CC users that this event was deleted
        Mail::to( 'juan@c-istudios.com' )
            ->cc($emails)
            ->send( new DeleteEvent( 'Cancelled Event', $event->event_date ) );
*/

        Session::flash('success', 'Event Deleted');
        return redirect()->back() ;
    }

// Controller is now refactored.

















以上是关于php Laravel服务类,来自Controller的重构逻辑的主要内容,如果未能解决你的问题,请参考以下文章

laravel 的数据表服务器端 php 类

php 具有服务类的Laravel数据表

创建 laravel 服务类

php输出控制output controll(header, ob_xxx)

使用 Redis 存储数据数组(来自 Laravel)

Laravel - PHP 致命错误:在迁移中找不到类“CreateMatchesTable”:刷新