【问题标题】:Creating helper for my application为我的应用程序创建助手
【发布时间】:2010-12-10 17:11:01
【问题描述】:

我一直在为 Facebook PHP API 创建一个帮助类,以避免重复使用大量代码。助手工作,但唯一的问题是它非常慢..我也想通了为什么!当我初始化类时,构造函数被调用了两次!我签入了我的代码,其他使用这个类的元素只调用它一次(这是类本身的东西)你能帮我弄清楚问题可能是什么吗?谢谢!

class FbHelper
{
    private $_fb;
    private $_user;

    function __construct()
    {
        // Initalize Facebook API with keys

        $this->_fb = new Facebook(array(
          'appId'  => 'xxxxxxxxxxx',
          'secret' => 'xxxxxxxxxxxxxxxxxxxxxx',
          'cookie' => true,
        ));

        // set the _user variable
        //
        $this->doLog("Called Constructor");
        //
        $this->_user = $this->UserSessionAuthorized();

        return $this;
    }

    function doLog($text)
    {
      // open log file  <----- THIS GETS CALLED TWICE EVERY TIME I INITIALIZE THE CLASS!!
      $filename = "form_ipn.log";
      $fh = fopen($filename, "a") or die("Could not open log file.");
      fwrite($fh, date("d-m-Y, H:i")." - $text\n") or die("Could not write file!");
      fclose($fh);
    }


    function getUser() { return $this->_user; }

    function getLoginUrl() { return $this->_fb->getLoginUrl(); }
    function getLogoutUrl() { return $this->_fb->getLogoutUrl(); }

    function UserSessionAuthorized()
    {
        // Checks if user is authorized, if is sends back user object

        $user = null;

        $session = $this->_fb->getSession();
        if (!$session) return false;
        try {
            $uid = $this->_fb->getUser();
            $user = $this->_fb->api('/me');
            if ($user) return $user;
            else return false;
            }
        catch (FacebookApiException $e) { return false; }
    }

    private function _rebuildSelectedFriends($selected_friends)
    {
        // Creates a new array with less data, more useful and less malicious

        $new = array();
        foreach ($selected_friends as $friend)
        {
            $f = array('id' => $friend['id'], 'name' => $friend['name']);
            $new[] = $f;
        }

        return $new;
    }

    function GetThreeRandomFriends()
    {
        $friends = $this->_fb->api('/me/friends');
        $n = rand(1, count($friends['data']) - 3);

        $selected_friends = array_slice($friends['data'], $n, 3);
        return $this->_rebuildSelectedFriends($selected_friends);
    }

    function UserExists($user_id)
    {
        try { $this->_fb->api('/' . $user_id . '/'); return true; }
        catch (Exception $e) { return false; }
    }

}

【问题讨论】:

    标签: php class constructor instance


    【解决方案1】:

    您必须调用FbHelper 类两次,因为您的doLog 函数在构造函数中,因此重复在您的应用程序中较高的位置而不是在此类本身中。

    【讨论】:

    • 是的.. 我也在考虑这个。有没有办法可以追踪谁调用了 FbHelper?谢谢
    • 您可以为此使用 debug_print_backtrace()。
    • 感谢您的回答!我发现了问题.. 使用 Codeigniter 并加载了两次该类!感谢大家的帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2018-03-05
    相关资源
    最近更新 更多