我是用OOP PHP做的吗?

时间:2010-08-25 18:11:56

标签: php oop scripting

Hello ,在我阅读了很多关于它的优点后,我现在正在用OOP PHP重写我的一个脚本(用ajax联系脚本)。

脚本变得更长但我认为这在oop中很好。我已经阅读了很多关于如何使用oop编写php的文章,但它仍然让我感到困惑。

代码

首先看一下脚本的这一部分:

/*
 * Validate the data that was given by the user
 */
public function isDataVaild() {
        if (array_filter($_POST, array($this, '_isDataEmpty'))) {
            $this->_error('Please fill all the required info');
            return false;
        }

        if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $this->_error('Please use a vaild email');
            return false;
        }

        if (!isset($_SESSION['captcha']) || $_SESSION['captcha'] != $_POST['captcha']) {
            $this->_error('Plese make sure you to enter the correct answer to the spam question');
            return false;
        }
        return true;
}

/*
 * Check is the values are empty or not
 */
protected function _isDataEmpty($val) {
    return(empty(trim($val)));
}

/*
 * Check if there is seesion in not valid or if it does not pass the exploit test
 */
public function isThereExploit () {
        if(array_filter($_POST, array($this, '_validateExploit')) || !$this->_isSessionValid()) {
            if($this->_ajax) {
                $this->_error('Exploit Detected');
            } else {
                $this->_error("<strong style='color: red'>Warning</strong>: An Exploitation attempt has been detected!");
            }
            return false;
        }
        return true;
}

/*
 * Test to see if the values have an exploit
 */
protected function _validateExploit($val) {
    $exploitPattrens = array('content-type', 'to:', 'bcc:', 'cc:', 'document.cookie', 'document.write', 'onclick', 'onload', '\n', '\r', '\t', '%0A', '%0D', '%08', '%09');

    foreach ($exploitPattrens as $exploit) {
        if (strpos($val, $exploit) !== false){
            return true;
        }
    }
    return false;
}

/*
 * Check if the session is vaild for this user
 */
protected  function _isSessionValid() {
    return ($_POST['token'] == $_SESSION['token']);
}

/*
 * Make some sanitizing to the givin value
 */
protected function _clean(&$variable) {
    $variable = trim(filter_var($variable, FILTER_SANITIZE_STRING));
    return $variable;
}

/*
 * Make the message ready to be sent by removing extra data and fixing the rest
 */
protected function _cleanMessage() {   
    foreach ($_POST as $key => &$val) {
        if ($key == 'email') {
            $val = strtolower($val);
        }
        if ($key == 'captcha' || $key == 'token') {
            unset($_POST[$key]);
        }
        $this->_clean($val);
    }
    return $_POST;
}

/*
 * Make the message after checking if the data is vaild and clean
 */
private function _makeMessage() {

    if(!$this->_ajax) {
        if(!$this->isDataVaild()) {
            return;
        }
    }

    if(!$this->isThereExploit()) {
        return;
    }

    $messageEntries = $this->_cleanMessage();

    $message_start = "<div dir='rtl' style='padding: 50px 0 100px;background: #eeeeee; font-family: Arial, Helvetica, sans-serif;'><h1 align='center' style='font-size: 24px; font-weight: bold;color: #989898;margin-bottom: 35px'>New Message</h1><table width='600' align='center' border='1' style='border-collapse: collapse; border: 1px solid #dddddd;font-size: 16px;' cellpadding='14' cellspacing='2'>";

    $message_end = "</table><p style='margin:0;color:#CACACA;font-size:10px;padding-top:20px;text-align:center;'><a style='color:#CACACA;text-decoration:none;' href='http://coolcontact.co.cc'>coolContact v1.2</a> - Developed &amp; Designed by Maher Salam, &copy; <a style='color:#CACACA;text-decoration:none;' href='http://coolworlds.net'>coolworlds.net</a></p></div>";

    $this->_message .= $message_start;

   foreach ($messageEntries as $id => $entrie) {

        $this->_message .= "<tr valign='top' bgcolor='#ffffff'><td width='90' align='left' style='color: #989898;'><b>" . $id . '</b></td><td>' . nl2br($entrie) . '</td></tr>';
        $this->_messagePlein .= $id . ': ' . nl2br($entrie) . '\r\n';
    }

    $this->_message .= $message_end;
}

/*
 * Send the message and return true if it worked
 */
public function send() {
        $this->_makeMessage();

        require 'class.phpmailer-lite.php';
        $mail = new PHPMailerLite();
        $mail->Mailer = 'mail';
        $mail->CharSet = 'UTF-8';

        $mail->SetFrom($this->_senderEmail, $this->_senderName);
        $mail->AddAddress($this->_recieverEmail);

        $mail->Subject = $this->_messageTitle;
        $mail->IsHTML(true);

        $mail->Body = $this->_message;
        $mail->AltBody = $this->_messagePleins;

        $mail->Send();

        return true;
}

我知道这可能是很多代码要阅读,但我想给你全部的图片:)

问题

有没有更好的方法来重写其中一些功能(如makeMessage())? 性能如何?

提前致谢。

1 个答案:

答案 0 :(得分:1)

首先我要说的是:面向对象的好选择!这是一种更好的编程方式。但...

在我看来,你的大部分方法都是静态方法。您需要捆绑所有具有共同点的方法,并将相关信息保存为类属性。这看起来像是一组在这种情况下意外地与彼此相关的函数,捆绑在一个类中。

此外,假设全局$ _POST变量中有多个键可用,这是错误的。类是可重用的。使用这些假设使它们不是。

除此之外,代码中还有一些奇怪的东西:

protected function _clean(&$variable) {
    $variable = trim(filter_var($variable, FILTER_SANITIZE_STRING));
    return $variable;
}

如果同时返回相同的变量,为什么还要将$变量作为参考?

根据空的文件:

empty() only checks variables as anything else will result in a parse error. 
In other words, the following will not work: empty(trim($name)). 

这将无法正常工作:

protected function _isDataEmpty($val) {
    return(empty(trim($val)));
}

同样,这是一个很好的尝试,但你需要更好地了解面向对象编程的含义。

  • statis与非静态之间的差异
  • 类属性及其访问方式
  • 制作受保护的方法和私有时

一旦你理解了OOP的基础知识,你会发现在OOP的精彩世界里还有更多的东西!

祝你好运!