Symfony2 将控制器逻辑重构为服务

Symfony2 refactoring controller logic into a service

我正在慢慢开始理解 Symfony2 中的东西是如何工作的。

我已经设置了一项服务,可以从实时提要中提取 json 数据。

我的控制器使用此服务来提取数据,然后将其保存到我的数据库中,我目前有 3 个实体,但可能还会有更多。

目前所有逻辑都在FantasyPro/DataBundle

我目前正在打破各种规则,例如将我的数据保存在控制器中的逻辑,所以我想我需要采用所有这些逻辑并将其放入我可以使用的服务中通过学说将提取的数据保存到我的数据库中。

我想在 DataBundle 中创建这个新的 PersistServce

由于该服务将需要使用我拥有的所有实体以及 api 服务的原则,我不确定如何让这些对服务可用。

可能值得一提的是,我打算创建命令,以便我可以 运行 cron 作业来提取这些数据,事实上,我认为我根本不需要控制器,因为它们只是内部使用,不用于生成请求。

我现在将它放在控制器中只是为了测试目的。

将此代码重构为服务的最佳方法是什么?

这是我凌乱的控制器代码

    <?php

namespace FantasyPro\DataBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FantasyPro\DataBundle\Entity\Stadium;
use FantasyPro\DataBundle\Entity\Team;
use FantasyPro\DataBundle\Entity\Player;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('DataBundle:Default:index.html.twig', array('name' => $name));
    }

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function updateStadiumAction(){
        //get list of stadiums

        $client = $this->container->get('fantasyapi');
        $stadiumData = $client->Stadiums();

        //get the entity manager
        $em = $this->getDoctrine()->getManager();
        $repo = $em->getRepository('DataBundle:Stadium');
        $log = array();

        $log = $this->addStadiumList( $stadiumData, $repo, $em, $log );

        $em->flush();
        return $this->render('DataBundle:Default:index.html.twig', array('log' => $log));
    }

    public function updateTeamAction()
    {

        //get list of teams

        $client = $this->container->get('fantasyapi');
        $teamData = $client->Teams();

        //get the entity manager
        $em = $this->getDoctrine()->getManager();
        $repo = $em->getRepository('DataBundle:Team');
        $log = array();

        $log = $this->addTeamList( $teamData, $repo, $em, $log, 'Team' );

        $em->flush();
        return $this->render('DataBundle:Default:index.html.twig', array('log' => $log));
    }

    public function updatePlayerAction()
    {
        //get the api client
        $client = $this->container->get('fantasyapi');

        //get the manager
        $em = $this->getDoctrine()->getManager();

        $teamRepo = $em->getRepository('DataBundle:Team');
        $playerRepo = $em->getRepository('DataBundle:Player');
        $log = array();

        //first we need to get a list of teams as players can only be collected via a teamID
        /** @var Team $teams */
        $teams = $client->Teams();
        //var_dump($teams);die;
        //loop through the teams and pull the playerData

        foreach($teams as $team){
            //log the team we are processing
            $logData = ['action' => 'Processing Players for:', 'itemID' => $team['TeamID'], 'itemName' => $team['FullName']];
            $log[] = $logData;

            //get list players on this team
            $players =  $client->Players(['Team' => $team['Key']]);
            //loop through the players

            $log = $this->addPlayerList( $players, $playerRepo, $em, $log, 'Added Active Player' );
        }

        //now get free agents

        $freeAgents = $client->FreeAgents();

        $log = $this->addPlayerList($freeAgents, $playerRepo, $em, $log, 'Free Agent');

        $em->flush();
        return $this->render('DataBundle:Default:index.html.twig', array('log' => $log));

    }

    public function parseDate($dateString)
    {
        if ($dateString) {

            preg_match( '/\/Date\((\d+)([-+])(\d+)\)\//', $dateString, $date );

            $timestamp = $date[1] / 1000;
            $operator  = $date[2];
            $hours     = $date[3] * 36; // Get the seconds

           // $datetime = new \DateTime($timestamp, new \DateTimeZone('America/New_York'));

            $datetime = new \DateTime();
            $datetime->setTimestamp($timestamp);
            $datetime->modify( $operator.$hours.' seconds' );
            $datetime->setTimezone(new \DateTimeZone('UTC'));


            //$datetime->format( 'd-m-Y H:i:s' );
            //var_dump( $datetime );
            //echo('*');
            return ($datetime);
        }
        return(null);
    }

    /**
     * @param Array $players
     * @param $playerRepo
     * @param $em
     * @param Array $log
     *
     * @param String $logTitle
     *
     * @return array
     */
    public function addPlayerList( $players, $playerRepo, $em, $log, $logTitle )
    {
        foreach ($players as $player) {
            // Get the current player in the list
            $criteria = array( 'playerID' => $player['PlayerID'] );

            /** @var Player $storedPlayer */
            $storedPlayer = $playerRepo->FindOneBy( $criteria );

            //var_dump($player);
            if ( ! $storedPlayer) {
                //no player exists with the PlayerID passed
                //create a new entry
                /** @var Player $entry */
                $entry = new Player();

                $entry->setTeam( $player['Team'] );
                $entry->setPlayerID( $player['PlayerID'] );
                $entry->setNumber( $player['Number'] );
                $entry->setFirstName( $player['FirstName'] );
                $entry->setLastName( $player['LastName'] );
                $entry->setPosition( $player['Position'] );
                $entry->setStatus( $player['Status'] );
                $entry->setHeight( $player['Height'] );
                $entry->setWeight( $player['Weight'] );
                //need to parse the date on this field
                $entry->setBirthDate( $this->parseDate( $player['BirthDate']));
                $entry->setCollege( $player['College'] );
                $entry->setExperience( $player['Experience'] );
                $entry->setFantasyPosition( $player['FantasyPosition'] );
                $entry->setActive( $player['Active'] );
                $entry->setPositionCategory( $player['PositionCategory'] );
                $entry->setName( $player['Name'] );
                $entry->setAge( $player['Age'] );
                $entry->setExperienceString( $player['ExperienceString'] );
                $entry->setBirthDateString( $player['BirthDateString'] );
                $entry->setPhotoUrl( $player['PhotoUrl'] );
                $entry->setByeWeek( $player['ByeWeek'] );
                $entry->setUpcomingGameOpponent( $player['UpcomingGameOpponent'] );
                $entry->setUpcomingGameWeek( $player['UpcomingGameWeek'] );
                $entry->setShortName( $player['ShortName'] );
                $entry->setAverageDraftPos( $player['AverageDraftPosition'] );
                $entry->setDepthPositionCategory( $player['DepthPositionCategory'] );
                $entry->setDepthPosition( $player['DepthOrder'] );
                $entry->setDepthDisplayOrder( $player['DepthDisplayOrder'] );
                $entry->setCurrentTeam( $player['CurrentTeam'] );
                $entry->setCollegeDraftTeam( $player['CollegeDraftTeam'] );
                $entry->setCollegeDraftYear( $player['CollegeDraftYear'] );
                $entry->setCollegeDraftRound( $player['CollegeDraftRound'] );
                $entry->setCollegeDraftPick( $player['CollegeDraftPick'] );
                $entry->setIsUndraftedFreeAgent( $player['IsUndraftedFreeAgent'] );
                $entry->setHeightFeet( $player['HeightFeet'] );
                $entry->setHeightInches( $player['HeightInches'] );
                $entry->setUpcomingOpponentRank( $player['UpcomingOpponentRank'] );
                $entry->setUpcomingOpponentPositionRank( $player['UpcomingOpponentPositionRank'] );
                $entry->setCurrentStatus( $player['CurrentStatus'] );
                $entry->setUpcomingSalary( $player['UpcomingSalary'] );

                $em->persist( $entry );
                $logData = [ 'action'   => 'Added '.$logTitle,
                             'itemID'   => $player['PlayerID'],
                             'itemName' => $player['Name']
                ];
                $log[] = $logData;
            } else {
                $storedPlayer->setPlayerID( $player['PlayerID'] );
                $storedPlayer->setTeam( $player['Team'] );
                $storedPlayer->setPlayerID( $player['PlayerID'] );
                $storedPlayer->setNumber( $player['Number'] );
                $storedPlayer->setFirstName( $player['FirstName'] );
                $storedPlayer->setLastName( $player['LastName'] );
                $storedPlayer->setPosition( $player['Position'] );
                $storedPlayer->setStatus( $player['Status'] );
                $storedPlayer->setHeight( $player['Height'] );
                $storedPlayer->setWeight( $player['Weight'] );
                //need to parse the date on this field
                $storedPlayer->setBirthDate( $this->parseDate( $player['BirthDate']));
                $storedPlayer->setCollege( $player['College'] );
                $storedPlayer->setExperience( $player['Experience'] );
                $storedPlayer->setFantasyPosition( $player['FantasyPosition'] );
                $storedPlayer->setActive( $player['Active'] );
                $storedPlayer->setPositionCategory( $player['PositionCategory'] );
                $storedPlayer->setName( $player['Name'] );
                $storedPlayer->setAge( $player['Age'] );
                $storedPlayer->setExperienceString( $player['ExperienceString'] );
                $storedPlayer->setBirthDateString( $player['BirthDateString'] );
                $storedPlayer->setPhotoUrl( $player['PhotoUrl'] );
                $storedPlayer->setByeWeek( $player['ByeWeek'] );
                $storedPlayer->setUpcomingGameOpponent( $player['UpcomingGameOpponent'] );
                $storedPlayer->setUpcomingGameWeek( $player['UpcomingGameWeek'] );
                $storedPlayer->setShortName( $player['ShortName'] );
                $storedPlayer->setAverageDraftPos( $player['AverageDraftPosition'] );
                $storedPlayer->setDepthPositionCategory( $player['DepthPositionCategory'] );
                $storedPlayer->setDepthPosition( $player['DepthOrder'] );
                $storedPlayer->setDepthDisplayOrder( $player['DepthDisplayOrder'] );
                $storedPlayer->setCurrentTeam( $player['CurrentTeam'] );
                $storedPlayer->setCollegeDraftTeam( $player['CollegeDraftTeam'] );
                $storedPlayer->setCollegeDraftYear( $player['CollegeDraftYear'] );
                $storedPlayer->setCollegeDraftRound( $player['CollegeDraftRound'] );
                $storedPlayer->setCollegeDraftPick( $player['CollegeDraftPick'] );
                $storedPlayer->setIsUndraftedFreeAgent( $player['IsUndraftedFreeAgent'] );
                $storedPlayer->setHeightFeet( $player['HeightFeet'] );
                $storedPlayer->setHeightInches( $player['HeightInches'] );
                $storedPlayer->setUpcomingOpponentRank( $player['UpcomingOpponentRank'] );
                $storedPlayer->setUpcomingOpponentPositionRank( $player['UpcomingOpponentPositionRank'] );
                $storedPlayer->setCurrentStatus( $player['CurrentStatus'] );
                $storedPlayer->setUpcomingSalary( $player['UpcomingSalary'] );

                $em->persist( $storedPlayer );
                $logData = [ 'action'   => 'Updated '.$logTitle,
                             'itemID'   => $player['PlayerID'],
                             'itemName' => $player['Name']
                ];
                $log[] = $logData;
            }
        }

        return ($log);
    }

    /**
     * @param Array $teamData
     * @param $repo
     * @param $em
     * @param String $logTitle
     *
     * @return array
     */
    public function addTeamList( $teamData, $repo, $em, $log, $logTitle )
    {
        foreach ($teamData as $team) {
            // Get the current team in the list
            $criteria = array( 'teamID' => $team['TeamID'] );
            //var_dump($criteria);
            /** @var Team $storedTeam */
            $storedTeam = $repo->FindOneBy( $criteria );

            if ( ! $storedTeam) {
                //no stadium exists with the StadiumID passed
                //create a new entry
                /** @var Team $entry */
                $entry = new Team();
                $entry->setTeamKey( $team['Key'] );
                $entry->setTeamID( $team['TeamID'] );
                $entry->setPlayerID( $team['PlayerID'] );
                $entry->setCity( $team['City'] );
                $entry->setName( $team['Name'] );
                $entry->setConference( $team['Conference'] );
                $entry->setDivision( $team['Division'] );
                $entry->setFullName( $team['FullName'] );
                $entry->setStadiumID( $team['StadiumID'] );
                $entry->setByeWeek( $team['ByeWeek'] );
                $entry->setAvergageDraftPos( $team['AverageDraftPosition'] );
                $entry->setAverageDraftPosPPR( $team['AverageDraftPositionPPR'] );
                $entry->setHeadCoach( $team['HeadCoach'] );
                $entry->setOffensiveCoordinator( $team['OffensiveCoordinator'] );
                $entry->setDefensiveCoordinator( $team['DefensiveCoordinator'] );
                $entry->setSpecialTeamsCoach( $team['SpecialTeamsCoach'] );
                $entry->setOffensiveScheme( $team['OffensiveScheme'] );
                $entry->setDefensiveScheme( $team['DefensiveScheme'] );
                $entry->setUpcomingSalary( $team['UpcomingSalary'] );
                $entry->setUpcomingOpponentRank( $team['UpcomingOpponentRank'] );
                $entry->setUpcomingOpponentPositionRank( $team['UpcomingOpponentPositionRank'] );

                $em->persist( $entry );
                $logData = [ 'action' => 'Added New '.$logTitle , 'itemID' => $team['TeamID'], 'itemName' => $team['Name'] ];
                $log[]   = $logData;
            } else {
                $storedTeam->setTeamKey( $team['Key'] );
                $storedTeam->setPlayerID( $team['PlayerID'] );
                $storedTeam->setCity( $team['City'] );
                $storedTeam->setName( $team['Name'] );
                $storedTeam->setConference( $team['Conference'] );
                $storedTeam->setDivision( $team['Division'] );
                $storedTeam->setFullName( $team['FullName'] );
                $storedTeam->setStadiumID( $team['StadiumID'] );
                $storedTeam->setByeWeek( $team['ByeWeek'] );
                $storedTeam->setAvergageDraftPos( $team['AverageDraftPosition'] );
                $storedTeam->setAverageDraftPosPPR( $team['AverageDraftPositionPPR'] );
                $storedTeam->setHeadCoach( $team['HeadCoach'] );
                $storedTeam->setOffensiveCoordinator( $team['OffensiveCoordinator'] );
                $storedTeam->setDefensiveCoordinator( $team['DefensiveCoordinator'] );
                $storedTeam->setSpecialTeamsCoach( $team['SpecialTeamsCoach'] );
                $storedTeam->setOffensiveScheme( $team['OffensiveScheme'] );
                $storedTeam->setDefensiveScheme( $team['DefensiveScheme'] );
                $storedTeam->setUpcomingSalary( $team['UpcomingSalary'] );
                $storedTeam->setUpcomingOpponentRank( $team['UpcomingOpponentRank'] );
                $storedTeam->setUpcomingOpponentPositionRank( $team['UpcomingOpponentPositionRank'] );

                $em->persist( $storedTeam );

                $logData = [ 'action' => 'Updated  '.$logTitle , 'itemID' => $team['TeamID'], 'itemName' => $team['Name'] ];
                $log[]   = $logData;
            }
        }

        return $log;
    }

    /**
     * @param Array $stadiumData
     * @param $repo
     * @param $em
     * @param $log
     *
     * @return array
     */
    public function addStadiumList( $stadiumData, $repo, $em, $log )
    {
        foreach ($stadiumData as $stadium) {
            // Get the current stadium in the list
            $criteria = array( 'stadiumID' => $stadium['StadiumID'] );
            //var_dump($criteria);
            /** @var Stadium $storedStadium */
            $storedStadium = $repo->FindOneBy( $criteria );

            if ( ! $storedStadium) {
                //no stadium exists with the StadiumID passed
                //create a new entry
                /** @var Stadium $entry */
                $entry = new Stadium();
                $entry->setStadiumID( $stadium['StadiumID'] );
                $entry->setName( $stadium['Name'] );
                $entry->setCity( $stadium['City'] );
                $entry->setState( $stadium['State'] );
                $entry->setCountry( $stadium['Country'] );
                $entry->setCapacity( $stadium['Capacity'] );
                $entry->setPlayingSurface( $stadium['PlayingSurface'] );
                $em->persist( $entry );
                $logData = [ 'action'   => 'Added New Stadium',
                             'itemID'   => $stadium['StadiumID'],
                             'itemName' => $stadium['Name']
                ];
                $log[]   = $logData;
            } else {
                $storedStadium->setStadiumID( $stadium['StadiumID'] );
                $storedStadium->setName( $stadium['Name'] );
                $storedStadium->setCity( $stadium['City'] );
                $storedStadium->setState( $stadium['State'] );
                $storedStadium->setCountry( $stadium['Country'] );
                $storedStadium->setCapacity( $stadium['Capacity'] );
                $storedStadium->setPlayingSurface( $stadium['PlayingSurface'] );
                $em->persist( $storedStadium );
                $logData = [ 'action'   => 'Updated Stadium',
                             'itemID'   => $stadium['StadiumID'],
                             'itemName' => $stadium['Name']
                ];
                $log[]   = $logData;
            }
        }

        return $log;
    }
}

对我来说处理您的目的的最佳方法是为您的实体创建扩展存储库 classes。

请参阅 Symfony2 - Doctrine 文档

在您的情况下,这可能是:

namespace SomeBundle\Repository;

use Doctrine\ORM\EntityRepository;

class PlayerRepository extends EntityRepository
{
    /**
     * @param Array  $players
     * @param        $playerRepo
     * @param        $em
     * @param Array  $log
     *
     * @param String $logTitle
     *
     * @return array
     */
    public function addPlayerList($players, $log, $logTitle)
    {
        foreach ($players as $player) {
            // Get the current player in the list
            $criteria = array('playerID' => $player['PlayerID']);

            /** @var Player $storedPlayer */
            $storedPlayer = $this->findOneBy($criteria);

            if (!$storedPlayer) {
                $storedPlayer = new Player();

                $logData = [
                    'action'   => 'Added '.$logTitle,
                    'itemID'   => $player['PlayerID'],
                    'itemName' => $player['Name']
                ];
                $log[]   = $logData;
            } else {
                $logData = [
                    'action'   => 'Updated '.$logTitle,
                    'itemID'   => $player['PlayerID'],
                    'itemName' => $player['Name']
                ];
                $log[]   = $logData;
            }

            $storedPlayer->setPlayerID($player['PlayerID']);
            $storedPlayer->setTeam($player['Team']);
            $storedPlayer->setPlayerID($player['PlayerID']);
            $storedPlayer->setNumber($player['Number']);
            $storedPlayer->setFirstName($player['FirstName']);
            $storedPlayer->setLastName($player['LastName']);
            $storedPlayer->setPosition($player['Position']);
            $storedPlayer->setStatus($player['Status']);
            $storedPlayer->setHeight($player['Height']);
            $storedPlayer->setWeight($player['Weight']);
            //need to parse the date on this field
            $storedPlayer->setBirthDate($this->parseDate($player['BirthDate']));
            $storedPlayer->setCollege($player['College']);
            $storedPlayer->setExperience($player['Experience']);
            $storedPlayer->setFantasyPosition($player['FantasyPosition']);
            $storedPlayer->setActive($player['Active']);
            $storedPlayer->setPositionCategory($player['PositionCategory']);
            $storedPlayer->setName($player['Name']);
            $storedPlayer->setAge($player['Age']);
            $storedPlayer->setExperienceString($player['ExperienceString']);
            $storedPlayer->setBirthDateString($player['BirthDateString']);
            $storedPlayer->setPhotoUrl($player['PhotoUrl']);
            $storedPlayer->setByeWeek($player['ByeWeek']);
            $storedPlayer->setUpcomingGameOpponent($player['UpcomingGameOpponent']);
            $storedPlayer->setUpcomingGameWeek($player['UpcomingGameWeek']);
            $storedPlayer->setShortName($player['ShortName']);
            $storedPlayer->setAverageDraftPos($player['AverageDraftPosition']);
            $storedPlayer->setDepthPositionCategory($player['DepthPositionCategory']);
            $storedPlayer->setDepthPosition($player['DepthOrder']);
            $storedPlayer->setDepthDisplayOrder($player['DepthDisplayOrder']);
            $storedPlayer->setCurrentTeam($player['CurrentTeam']);
            $storedPlayer->setCollegeDraftTeam($player['CollegeDraftTeam']);
            $storedPlayer->setCollegeDraftYear($player['CollegeDraftYear']);
            $storedPlayer->setCollegeDraftRound($player['CollegeDraftRound']);
            $storedPlayer->setCollegeDraftPick($player['CollegeDraftPick']);
            $storedPlayer->setIsUndraftedFreeAgent($player['IsUndraftedFreeAgent']);
            $storedPlayer->setHeightFeet($player['HeightFeet']);
            $storedPlayer->setHeightInches($player['HeightInches']);
            $storedPlayer->setUpcomingOpponentRank($player['UpcomingOpponentRank']);
            $storedPlayer->setUpcomingOpponentPositionRank($player['UpcomingOpponentPositionRank']);
            $storedPlayer->setCurrentStatus($player['CurrentStatus']);
            $storedPlayer->setUpcomingSalary($player['UpcomingSalary']);

        }

        return ($log);
    }
}

另外,我宁愿创建日期解析器 class 来解析此存储库中的日期,例如

$date = (new CustomDateTimeParser('your fancy date string here'))->getDateTime();