更好的数组和函数调用实践

时间:2013-07-26 06:01:55

标签: php

我正在寻找一个PHP语言更好实践的答案。我有以下代码。将输出函数列表发送到显示器是否更好,或者我应该为输出功能显示一个数组。如果您有评论或答案,请提供支持您答案的任何文档,以便包括我在内的任何人可以在将来查看此材料。我已经包含了输出函数来显示我如何将消息输出到browswers但是我正在考虑使用flashdata进行显示,但是当我有不同类型的消息(例如信息,警告,成功消息)时,我想知道如何使用它。 / p>

if (!$this->form_is_valid())
{
    $this->output('The form did not validate successfully!', 
                    'Form Not Validated', 'Error');
    return;
}

public function output($message, $title, $status)
{
    switch (strtoupper($status))
    {
        default:
        case 'ERROR':
            $status = 'Error';
            break;
        case 'NOTICE':
            $status = 'Notice';
            break;
        case 'SUCCESS':
            $status = 'Success';
            break;
    }
    $this->output->set_content_type('application/json')->set_output(json_encode(array
        (
        'output_status' => $status,
        'output_title' => $title,
        'output_message' => $message)));
}

1 个答案:

答案 0 :(得分:2)

更好的选择是将对象传递给输出方法:

<?php
interface Message
{
  public function getContents();
  public function getSummary();
  public function getType();
}

abstract class AbstractMessage() implements Message
{
  protected $type;
  protected $contents;
  protected $summary;

  protected function __construct($contents, $summary) {
    $this->contents = $contents;
    $this->summary = $summary;
  }

  public function getContents() {
    return $this->contents;
  }

  public function getSummary() {
    return $this->summary;
  }

  public function getType() {
    return $this->type;
  }
}

class ErrorMessage() extends AbstractMessage
{
  public function __construct($contents, $summary) {
    parent::__construct($contents, $summary);
    $this->type = 'Error';
  }
}

class InfoMessage() extends AbstractMessage
{
  ...
}

...

if (!$this->form_is_valid())
{
  $this->output(new ErrorMessage(
    'The form did not validate successfully!', 
    'Form Not Validated',
    'Error'
  ));
  return;
}