PHP面向对象的Web应用程序 [英] PHP Object Oriented Web Application

查看:102
本文介绍了PHP面向对象的Web应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为"Layout"的类用于页面的布局,另一个名为"User"的类用于用户.

I have a class called "Layout" for the layout of the page, another class called "User" for the user.

我创建的每个页面都实例化一个新的布局.

Every page I create, I instantiate a new Layout.

用户登录时,将实例化一个新用户.

When a user logs in, there is a new User instantiated.

如何获取布局类的实例来了解实例化的用户?我还可以将User的整个实例保存在会话变量中.我认为这是个坏主意.最佳做法是什么?

How do I get an instance of the layout class to know about the instantiated user? I could also save the entire instance of the User in a session variable. I assume that's a bad idea though. What are the best practices for this?

class User
{
  var $userid;
  var $email;
  var $username;

  function User($user)
  {
     $this->userid = $this->getUid($user);
     $this->email = $this->getEmail($user);
     $this->username = $user;
  }
  function getUid($u)
  {
     ...
  }

  function getEmail($u)
  {
     ...
  }
}

class Layout
{

    var $var1;
    var $var2;
    var $var3;

    function Layout()
    {
        //defaults...
    } 


    function function1()
    {
        echo "something";
    }


   function function2()
   {
        echo "some other stuff";
   }

   function function3()
   {
      echo "something else";
   }

}

例如,在index.php中,我将执行以下操作:

so in index.php, for example, i would do the following:

include "user.php"
include "layout.php"

$homelayout = new Layout();
$homelayout->function1();
$homelayout->function2();
$homelayout->function3();

现在让我们说,在login.php中有人登录了:

now let's say that in login.php someone logged in:

include "layout.php"
include "user.php"

if(userAuthSuccess)
{
    $currentUser = new User($_POST['username']);
}

只要用户尚未注销,什么是从所有php文件访问$ currentUser及其成员变量(如$ currentUser-> email等)的最佳方法?

what is the best way to gain access to $currentUser and it's member variables such as $currentUser->email, etc. from all php files from here on out, as long as the user hasn't logged out?

推荐答案

由于每个请求只有一个User,因此程序的每次运行都只有一个User,因此可以将"User"作为Singleton类,在这里描述:

Since there will be only one User for every request and thus for every run of your program, this would be a case to make "User" a Singleton class as described here:

http://php.net/manual/en/language.oop5 .patterns.php

这将为其他类提供一种方法来引用当前用户,而不会访问错误的实例,因为只有一个实例.

That would provide the one way for other classes to refer to the current user without the chance of accessing the wrong instance since there is only one.

免责声明: 是的,我知道Singeltons通常在错误的地方用于错误的目的,并且有些人倾向于将此问题归咎于模式,而不是将其误用于某些臭味的代码. 但是,这是Singelton模式的完美用例.

DISCLAIMER: Yes, I know that Singeltons are often used at the wrong places for the wrong purpose and some people tend to blame this problem on the pattern instead of the people who misused it for some smelly code. This however is a perfectly good use case for the Singelton pattern.

这篇关于PHP面向对象的Web应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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