首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >提高CakePHP中的代码质量

提高CakePHP中的代码质量
EN

Stack Overflow用户
提问于 2009-07-03 08:43:48
回答 3查看 2.6K关注 0票数 13

我已经使用CakePHP几个星期了,这是一次很棒的体验。我已经成功地以惊人的速度移植了一个网站,我甚至添加了一系列我原本计划但从未实现的新功能。

看看下面的两个控制器,它们允许用户将高级状态添加到链接到其帐户的站点之一。他们感觉不是很“卡基”,有没有什么可以改进的地方?

PremiumSites控制器处理注册过程,并最终拥有其他相关信息,如历史记录。

代码语言:javascript
复制
class PremiumSitesController extends AppController {

    var $name = 'PremiumSites';

    function index() {
        $cost = 5;

        //TODO: Add no site check

        if (!empty($this->data)) {
            if($this->data['PremiumSite']['type'] == "1") {
                $length = (int) $this->data['PremiumSite']['length'];
                $length++;
                $this->data['PremiumSite']['upfront_weeks'] = $length;
                $this->data['PremiumSite']['upfront_expiration'] = date('Y-m-d H:i:s', strtotime(sprintf('+%s weeks', $length)));
                $this->data['PremiumSite']['cost'] = $cost * $length;
            } else {
                $this->data['PremiumSite']['cost'] = $cost;
            }

            $this->PremiumSite->create();
            if ($this->PremiumSite->save($this->data)) {
                $this->redirect(array('controller' => 'paypal_notifications', 'action' => 'send', $this->PremiumSite->getLastInsertID()));
            } else {
                $this->Session->setFlash('Please fix the problems below', true, array('class' => 'error'));
            }
        }

        $this->set('sites',$this->PremiumSite->Site->find('list',array('conditions' => array('User.id' => $this->Auth->user('id'), 'Site.is_deleted' => 0), 'recursive' => 0)));
    }

}

PaypalNotifications控制器处理与贝宝的交互。

代码语言:javascript
复制
class PaypalNotificationsController extends AppController {

    var $name = 'PaypalNotifications';

    function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('process');
    }

    /**
     * Compiles premium info and send the user to Paypal
     * 
     * @param integer $premiumID an id from PremiumSite 
     * @return null
     */
    function send($premiumID) {

        if(empty($premiumID)) {
            $this->Session->setFlash('There was a problem, please try again.', true, array('class' => 'error'));
            $this->redirect(array('controller' => 'premium_sites', 'action' => 'index'));
        }

        $data = $this->PaypalNotification->PremiumSite->find('first', array('conditions' => array('PremiumSite.id' => $premiumID), 'recursive' => 0));

        if($data['PremiumSite']['type'] == '0') {
            //Subscription
            $paypalData = array(
                'cmd' => '_xclick-subscriptions',
                'business'=> '',
                'notify_url' => '',
                'return' => '',
                'cancel_return' => '',
                'item_name' => '',
                'item_number' => $premiumID,
                'currency_code' => 'USD',
                'no_note' => '1',
                'no_shipping' => '1',
                'a3' => $data['PremiumSite']['cost'],
                'p3' => '1',
                't3' => 'W',
                'src' => '1',
                'sra' => '1'
            );

            if($data['Site']['is_premium_used'] == '0') {
                //Apply two week trial if unused
                $trialData = array(
                    'a1' => '0',
                    'p1' => '2',
                    't1' => 'W',
                );
                $paypalData = array_merge($paypalData, $trialData);
            }
        } else {
            //Upfront payment

            $paypalData = array(
                'cmd' => '_xclick',
                'business'=> '',
                'notify_url' => '',
                'return' => '',
                'cancel_return' => '',
                'item_name' => '',
                'item_number' => $premiumID,
                'currency_code' => 'USD',
                'no_note' => '1',
                'no_shipping' => '1',
                'amount' => $data['PremiumSite']['cost'],
            );
        }

        $this->layout = null;
        $this->set('data', $paypalData);
    }

    /**
     * IPN Callback from Paypal. Validates data, inserts it
     * into the db and triggers __processTransaction()
     * 
     * @return null
     */
    function process() {
        //Original code from http://www.studiocanaria.com/articles/paypal_ipn_controller_for_cakephp
        //Have we been sent an IPN here...
        if (!empty($_POST)) {
            //...we have so add 'cmd' 'notify-validate' to a transaction variable
            $transaction = 'cmd=_notify-validate';
            //and add everything paypal has sent to the transaction
            foreach ($_POST as $key => $value) {
                $value = urlencode(stripslashes($value));
                $transaction .= "&$key=$value";
            }
            //create headers for post back
            $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
            $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
            $header .= "Content-Length: " . strlen($transaction) . "\r\n\r\n";
            //If this is a sandbox transaction then 'test_ipn' will be set to '1'
            if (isset($_POST['test_ipn'])) {
                $server = 'www.sandbox.paypal.com';
            } else {
                $server = 'www.paypal.com';
            }
            //and post the transaction back for validation
            $fp = fsockopen('ssl://' . $server, 443, $errno, $errstr, 30);
            //Check we got a connection and response...
            if (!$fp) {
                //...didn't get a response so log error in error logs
                $this->log('HTTP Error in PaypalNotifications::process while posting back to PayPal: Transaction=' .
                    $transaction);
            } else {
                //...got a response, so we'll through the response looking for VERIFIED or INVALID
                fputs($fp, $header . $transaction);
                while (!feof($fp)) {
                    $response = fgets($fp, 1024);
                    if (strcmp($response, "VERIFIED") == 0) {
                        //The response is VERIFIED so format the $_POST for processing
                        $notification = array();

                        //Minor change to use item_id as premium_site_id
                        $notification['PaypalNotification'] = array_merge($_POST, array('premium_site_id' => $_POST['item_number']));
                        $this->PaypalNotification->save($notification);

                        $this->__processTransaction($this->PaypalNotification->id);
                    } else
                        if (strcmp($response, "INVALID") == 0) {
                            //The response is INVALID so log it for investigation
                            $this->log('Found Invalid:' . $transaction);
                        }
                }
                fclose($fp);
            }
        }
        //Redirect
        $this->redirect('/');
    }

    /**
     * Enables premium site after payment
     * 
     * @param integer $id uses id from PaypalNotification
     * @return null
     */
    function __processTransaction($id) {
        $transaction = $this->PaypalNotification->find('first', array('conditions' => array('PaypalNotification.id' => $id), 'recursive' => 0));
        $txn_type = $transaction['PaypalNotification']['txn_type'];

        if($txn_type == 'subscr_signup' || $transaction['PaypalNotification']['payment_status'] == 'Completed') {
            //New subscription or payment
            $data = array(
                'PremiumSite' => array(
                    'id' => $transaction['PremiumSite']['id'],
                    'is_active' => '1',
                    'is_paid' => '1'
                ),
                'Site' => array(
                    'id' => $transaction['PremiumSite']['site_id'],
                    'is_premium' => '1'
                )
            );

            //Mark trial used only on subscriptions
            if($txn_type == 'subscr_signup') $data['Site']['is_premium_used'] = '1';

            $this->PaypalNotification->PremiumSite->saveAll($data);

        } elseif($txn_type == 'subscr-cancel' || $txn_type == 'subscr-eot') {
            //Subscription cancellation or other problem
            $data = array(
                'PremiumSite' => array(
                    'id' => $transaction['PremiumSite']['id'],
                    'is_active' => '0',
                ),
                'Site' => array(
                    'id' => $transaction['PremiumSite']['site_id'],
                    'is_premium' => '0'
                )
            );

            $this->PaypalNotification->PremiumSite->saveAll($data);
        }


    }

    /**
     * Used for testing
     * 
     * @return null
     */
    function index() {
        $this->__processTransaction('3');
    }
}

/views/paypal_notifications/send.ctp

发送用户到贝宝连同所有必要的数据

代码语言:javascript
复制
echo "<html>\n";
echo "<head><title>Processing Payment...</title></head>\n";
echo "<body onLoad=\"document.form.submit();\">\n";
echo "<center><h3>Redirecting to paypal, please wait...</h3></center>\n";

echo $form->create(null, array('url' => 'https://www.sandbox.paypal.com/cgi-bin/webscr', 'type' => 'post', 'name' => 'form'));

foreach ($data as $field => $value) {
    //Using $form->hidden sends in the cake style, data[PremiumSite][whatever]
    echo "<input type=\"hidden\" name=\"$field\" value=\"$value\">";
}

echo $form->end();

echo "</form>\n";
echo "</body></html>\n";

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-07-03 14:39:43

PHP第1课:不要使用的超全局变量

  • $_POST = $this->params['form'];
  • $_GET = $this->params['url'];
  • $_GLOBALS = Configure::write('App.category.variable', 'value');
  • $_SESSION (视图)= (helper)
  • $_SESSION (component)
  • $_SESSION['Auth']['User'] (控制器)= $this->Auth->user();

$session->read(); = $this->Session->read();

$_POST的替代品:

代码语言:javascript
复制
<?php
    ...
    //foreach ($_POST as $key => $value) {
    foreach ($this->params['form'] as $key => $value) {
    ...
    //if (isset($_POST['test_ipn'])) {
    if (isset($this->params['form']['test_ipn'])) {
    ...
?>

第2课:视图用于(与用户)共享

代码文档“编译高级信息并将用户发送到贝宝”不会将用户发送到PayPal。是否在视图中重定向?

代码语言:javascript
复制
<?php
    function redirect($premiumId) {
        ...
        $this->redirect($url . '?' . http_build_query($paypalData), 303);
    }

重定向到控制器的末尾并删除视图。:)

第3课:数据操作属于模型层

代码语言:javascript
复制
<?php
class PremiumSite extends AppModel {
    ...
    function beforeSave() {
        if ($this->data['PremiumSite']['type'] == "1") {
            $cost = Configure::read('App.costs.premium');
            $numberOfWeeks = ((int) $this->data['PremiumSite']['length']) + 1;
            $timestring = String::insert('+:number weeks', array(
                'number' => $numberOfWeeks,
            ));
            $expiration = date('Y-m-d H:i:s', strtotime($timestring));
            $this->data['PremiumSite']['upfront_weeks'] = $weeks;
            $this->data['PremiumSite']['upfront_expiration'] = $expiration;
            $this->data['PremiumSite']['cost'] = $cost * $numberOfWeeks;
        } else {
            $this->data['PremiumSite']['cost'] = $cost;
        }
        return true;
    }
    ...
}
?>

第4课:模型不仅仅用于数据库访问

将记录的代码"Enables site after payment“移至PremiumSite模型,并在付款后调用:

代码语言:javascript
复制
<?php
class PremiumSite extends AppModel {
    ...
    function enable($id) {
        $transaction = $this->find('first', array(
            'conditions' => array('PaypalNotification.id' => $id),
            'recursive' => 0,
        ));
        $transactionType = $transaction['PaypalNotification']['txn_type'];

        if ($transactionType == 'subscr_signup' ||
            $transaction['PaypalNotification']['payment_status'] == 'Completed') {
            //New subscription or payment
            ...
        } elseif ($transactionType == 'subscr-cancel' ||
            $transactionType == 'subscr-eot') {
            //Subscription cancellation or other problem
            ...
        }
        return $this->saveAll($data);
    }
    ...
}
?>

您可以使用$this->PaypalNotification->PremiumSite->enable(...);从控制器调用,但我们不会这样做,所以让我们将它们混合在一起……

第5课:数据源很酷

将您的PayPal IPN交互抽象到一个供模型使用的数据源中。

配置在app/config/database.php中进行

代码语言:javascript
复制
<?php
class DATABASE_CONFIG {
    ...
    var $paypal = array(
        'datasource' => 'paypal_ipn',
        'sandbox' => true,
        'api_key' => 'w0u1dnty0ul1k3t0kn0w',
    }
    ...
}
?>

数据源处理web服务请求(app/models/datasources/paypal_ipn_source.php)

代码语言:javascript
复制
<?php
class PaypalIpnSource extends DataSource {
    ...
    var $endpoint = 'http://www.paypal.com/';
    var $Http = null;
    var $_baseConfig = array(
        'sandbox' => true,
        'api_key' => null,
    );

    function _construct() {
        if (!$this->config['api_key']) {
            trigger_error('No API key specified');
        }
        if ($this->config['sandbox']) {
            $this->endpoint = 'http://www.sandbox.paypal.com/';
        }
        $this->Http = App::import('Core', 'HttpSocket'); // use HttpSocket utility lib
    }

    function validate($data) {
       ...
       $reponse = $this->Http->post($this->endpoint, $data);
       ..
       return $valid; // boolean
    }
    ...
}
?>

让模型完成工作(app/models/paypal_notification.php)

只有在通知有效时才会保存通知,只有在保存通知后才会启用网站

代码语言:javascript
复制
<?php
class PaypalNotification extends AppModel {
    ...
    function beforeSave() {
        $valid = $this->validate($this->data);
        if (!$valid) {
            return false;
        }
        //Minor change to use item_id as premium_site_id
        $this->data['PaypalNotification']['premium_site_id'] = 
            $this->data['PaypalNotification']['item_number'];
        /*
        $this->data['PaypalNotification'] = am($this->data, // use shorthand functions
            array('premium_site_id' => $this->data['item_number']));
        */
        return true;
    }
    ...
    function afterSave() {
        return $this->PremiumSite->enable($this->id);
    }
    ...
    function validate($data) {
        $paypal = ConnectionManager::getDataSource('paypal');
        return $paypal->validate($data);
    }
    ...
?>

控制器是愚蠢的。(app/controllers/paypal_notifications_controller.php)

“你是帖子吗?不是吗?……那我根本就不存在。”现在,此操作只是喊出“我保存了发布的PayPal通知!”

代码语言:javascript
复制
<?php
class PaypalNotificationsController extends AppModel {
    ...
    var $components = array('RequestHandler', ...);
    ...
    function callback() {
        if (!$this->RequestHandler->isPost()) { // use RequestHandler component
            $this->cakeError('error404');
        }
        $processed = $this->PaypalNotification->save($notification);
        if (!$processed) {
            $this->cakeError('paypal_error');
        }
    }
    ...
}
?>

奖励轮:使用提供的库,而不是原生PHP.

有关以下内容的示例,请参考前面的课程:

  • String代替sprintf
  • HttpSocket代替functions
  • RequestHandler用checks
  • am代替array_merge

代替fsock

这些可以防止编码错误,减少代码量和/或增加可读性。

票数 28
EN

Stack Overflow用户

发布于 2009-07-03 22:16:29

除了deizel提到的所有东西(非常棒的帖子),记住一个基本的蛋糕原则:胖模型,瘦控制器。您可以检查this example,但其基本思想是将所有数据乱码放入您的模型中。您的控制器应该(主要)只是模型和视图之间的一个链接。您的PremiumSitesController::index()就是一个完美的例子,它说明了应该在模型中的某个位置(正如deizel所指出的)。

Chris Hartjes也写了一个book about refactoring,如果你真的想学习,你可能会想看看它(它不是免费的,但很便宜)。此外,Matt Curry有一个很酷的名字:Super Awesome Advanced CakePHP Tips,完全免费下载。这两本书都值得一读。

我还想介绍我自己的一篇关于cake的文章,我相信它对cake的代码质量很重要:Code formatting and readability。虽然我能理解如果人们不同意..:-)

票数 5
EN

Stack Overflow用户

发布于 2009-07-03 14:25:46

好吧,我要指出这两件事:

  1. 你有一大堆硬编码的配置东西...使用cake的Configure可以做到这一点。就像第一个控制器中的$cost变量,或者$paypalData ...如果你愿意,你可以从其他地方获取(例如,flash应该来自语言文件),但不要将配置和实现混为一谈……这将使类的可读性更好,维护也更容易……
  2. 将所有套接字内容封装到一个新的助手类中……你可能会需要它的地方。实际上,它使发生的事情变得模糊。另外,考虑移出你的boa控制器的其他部分...例如,只需在它下面添加一些其他类,就可以实现……你应该总是尝试使用小而简洁的前端控制器,因为这会让你更容易理解发生了什么……如果有人关心实现细节,可以查看相应的类...

这就是我认为的可笑之处。

问候

back2dos

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1078418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档