编写这样的PHP代码的最佳做法是什么

时间:2014-11-16 08:08:15

标签: php

此代码来自我的Kohana项目。如何让它更美丽? 我应该使用try-catch吗?怎么不写exit()两次?

public function action_index()
{
    $id = $this->request->query('id');
    if (!empty($id)) {
        $ticket = ORM::factory('ticket')
            ->where('id', '=', $id)
            ->find();
        if (!empty($ticket)) {
            $event = ORM::factory('event')
                ->where('id', '=', $ticket->event_id)
                ->find();
            if (!empty($event)) {
                $this->template->ticket = $ticket->id;
                $this->template->name = $ticket->name;
                $this->template->event = $event->title;
            } else {
                exit();
            }
        } else {
            exit();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

代码在这种风格下变得更具可读性(恕我直言):

public function action_index()
{
    $id = $this->request->query('id');
    if (empty($id)) {
        return; //or exit() if you really need it
    }

    $ticket = ORM::factory('ticket')
        ->where('id', '=', $id)
        ->find();
    if (empty($ticket)) {
        return; //or exit() if you really need it
    }

    $event = ORM::factory('event')
        ->where('id', '=', $ticket->event_id)
        ->find();
    if (empty($event)) {
        return; //or exit() if you really need it
    }

    $this->template->ticket = $ticket->id;
    $this->template->name = $ticket->name;
    $this->template->event = $event->title;
}

答案 1 :(得分:1)

我通常不使用if语句的单行形式,但在这种情况下,我认为它们对可读性有很大帮助。

public function action_index(){
    $id = $this->request->query('id');

    if (empty($id)) return;

    $ticket = ORM::factory('ticket')
        ->where('id', '=', $id)
        ->find();

    if (empty($ticket)) exit();

    $event = ORM::factory('event')
        ->where('id', '=', $ticket->event_id)
        ->find();

    if (empty($event)) exit();

    $this->template->ticket = $ticket->id;
    $this->template->name = $ticket->name;
    $this->template->event = $event->title;     
}