为我的应用程序创建帮助器

时间:2010-12-10 17:11:01

标签: php class constructor instance

我一直在为PHP 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; }
    }

}

1 个答案:

答案 0 :(得分:1)

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