类中的PHP异常 [英] PHP Exceptions in Classes

查看:41
本文介绍了类中的PHP异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的朋友编写一个Web应用程序(PHP),并决定使用Java的有限OOP培训。

I'm writing a web application (PHP) for my friend and have decided to use my limited OOP training from Java.

我的问题是什么是最好的在我的类/应用程序中指出特定的关键事件失败而没有真正破坏我的页面的方式。

My question is what is the best way to note in my class/application that specific critical things failed without actually breaking my page.

我的问题是我有一个对象 SummerCamper,它需要一个camper_id从数据库将所有必要的数据加载到对象中的参数。假设有人在查询字符串中指定了不存在的camper_id,我将其传递给对象构造函数,加载失败。我目前还没有办法让我从构造函数中返回false。

My problem is I have an Object "SummerCamper" which takes a camper_id as it's argument to load all of the necessary data into the object from the database. Say someone specifies a camper_id in the query string that does not exist, I pass it to my objects constructor and the load fails. I don't currently see a way for me to just return false from the constructor.

我已经读过,我可以使用Exceptions来做到这一点,如果没有记录,则抛出异常可以在数据库中找到,或者在从应用程序等输入的camper_id时某种验证失败。

I have read I could possibly do this with Exceptions, throwing an exception if no records are found in the database or if some sort of validation fails on input of the camper_id from the application etc.

但是,我还没有真正找到提醒我的好方法对象加载失败的程序。我尝试从CATCH内返回false,但该对象仍保留在我的php页面中。我确实知道,如果加载失败,我可以放入变量$ is_valid = false,然后使用get方法检查Object,但我认为可能会有更好的方法。

However, I have not really found a great way to alert my program that the Object Load has failed. I tried returning false from within the CATCH but the Object still persists in my php page. I do understand I could put a variable $is_valid = false if the load fails and then check the Object using a get method but I think there may be better ways.

什么负载失败时实现对象基本终止的最佳方法是什么?我应该从构造函数外部将数据加载到对象中吗?我应该研究某种设计模式吗?

What is the best way of achieving the essential termination of an object if a load fails? Should I load data into the object from outside the constructor? Is there some sort of design pattern that I should look into?

任何帮助将不胜感激。

function __construct($camper_id){
        try{
            $query = "SELECT * FROM campers WHERE camper_id = $camper_id";
            $getResults = mysql_query($query);

            $records = mysql_num_rows($getResults);

            if ($records != 1) {
                throw new Exception('Camper ID not Found.');
            }

            while($row = mysql_fetch_array($getResults))
            {
                $this->camper_id = $row['camper_id'];
                $this->first_name = $row['first_name'];
                $this->last_name = $row['last_name'];
                $this->grade = $row['grade'];
                $this->camper_age = $row['camper_age'];
                $this->camper_gender = $row['gender'];
                $this->return_camper = $row['return_camper'];
            }
        }
        catch(Exception $e){
            return false;
        }



    }


推荐答案

PHP中的构造函数将始终返回 void 。此

A constructor in PHP will always return void. This

public function __construct()
{
    return FALSE;
}

不起作用。 在构造函数中引发异常

public function __construct($camperId)
{
    if($camperId === 1) {
        throw new Exception('ID 1 is not in database');
    }
}

除非您在某个地方抓到脚本,否则它将终止脚本执行

would terminate script execution unless you catch it somewhere

try { 
    $camper = new SummerCamper(1);
} catch(Exception $e) {
    $camper = FALSE;
}

您可以将上面的代码移到静态方法来创建它的实例,而不是使用 new 关键字(我在Java中很常见)

You could move the above code into a static method of SummerCamper to create instances of it instead of using the new keyword (which is common in Java I heard)

class SummerCamper
{
    protected function __construct($camperId)
    {
        if($camperId === 1) {
            throw new Exception('ID 1 is not in database');
        }
    }
    public static function create($camperId)
    {
        $camper = FALSE;
        try {
            $camper = new self($camperId);
        } catch(Exception $e) {
            // uncomment if you want PHP to raise a Notice about it
            // trigger_error($e->getMessage(), E_USER_NOTICE);
        }
        return $camper;
    }
}

这样您可以做到

$camper = SummerCamper::create(1);

并在<$ c $中获得 FALSE $ camper_id 不存在时,c> $ camper 。由于静电被认为是有害的,因此您可能想使用Factory。

and get FALSE in $camper when the $camper_id does not exist. Since statics are considered harmful, you might want to use a Factory instead.

另一个选择是将数据库访问与 SummerCamper 完全分离。基本上, SummerCamper 是仅应关注 SummerCamper 事物的实体。如果您了解它如何保持自身的知识,那么您实际上就是在创建 ActiveRecord RowDataGateway 。您可以使用 DataMapper 方法:

Another option would be to decouple the database access from the SummerCamper altogether. Basically, SummerCamper is an Entity that should only be concerned about SummerCamper things. If you give it knowledge how to persist itself, you are effectively creating an ActiveRecord or RowDataGateway. You could go with a DataMapper approach:

class SummerCamperMapper
{
    public function findById($id)
    {
        $camper = FALSE;
        $data = $this->dbAdapter->query('SELECT id, name FROM campers where ?', $id);
        if($data) {
            $camper = new SummerCamper($data);
        }
        return $camper;
    }
}

和您的实体

class SummerCamper
{
    protected $id;
    public function __construct(array $data)
    {
        $this->id = data['id'];
        // other assignments
    }
}

DataMapper有点更加复杂,但是它为您提供了解耦的代码,最终更易于维护和灵活。因此,看看这些主题有很多问题。

DataMapper is somewhat more complicated but it gives you decoupled code which is more maintainable and flexible in the end. Have a look around SO, there is a number of questions on these topics.

这篇关于类中的PHP异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆