PHP中的Singleton模式。...如何在请求之间保存状态 [英] Singleton Pattern In PHP.... How Can I Save State Between Requests

查看:66
本文介绍了PHP中的Singleton模式。...如何在请求之间保存状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用静态变量和单例模式,我认为创建一个简单的购物车就足够容易了,该购物车可以记住加载另一页时购物车中的物品。

With the use of static variables and the singleton pattern, I thought that it would be easy enough to create a simple shopping cart that remembered what items where in the cart when another page was loaded.

我有一个购物车问题,当页面刷新时不记得里面已经有什么了。

I am having a problem of the shopping cart not remembering what was already in it when the page is refreshed.

下面的代码是否有问题,还是应该只使用全局变量或mysql数据库?

Is there a problem with my code below or should I just use globals or a mysql database.

存储状态的最佳方法是什么。

What is the best way to go about storing state..

<?php
//create a singleton class
class shoppingCart {

    private static $_shoppingCartItems = array();
    private static $_instance = null;

    private function __construct(){

    }

    public static function getInstance(){
        if(self::$_instance == null)
            self::$_instance = new shoppingCart();
        return self::$_instance;            
    }


    public function add(ShoppingItem $item){
        $this->_shoppingCartItems[] = $item;
    }

    public function cartCount(){                 
        return count($this->_shoppingCartItems);
    }  
}
?>



实施



Implementation

$item = new shoppingItem();

$shoppingCart = shoppingCart::getInstance();
$shoppingCart->add($item);
$shoppingCart->add($item);

//should increment by 2 on each page load but it doesn't
echo $shoppingCart->cartCount(); 


推荐答案

我想我可以在那里看到您的思维模式,但是您尝试做的事情在很多方面都是错误的。

I think I can see your thought pattern there but what you're trying to do is wrong in many ways.

Singleton是反模式,应不惜一切代价避免。请参阅戈登的这个好答案

The Singleton is an anti-pattern and should be avoided at all costs. See this great answer by Gordon for the why.

仅在PHP中所做的任何事情都不会帮助您在两个请求之间保持状态。您的 $ shoppingCart 是为每个请求从头开始创建的,实际上,整个应用程序都是这样。您不应尝试将数据保留在对象中,而应在每次请求后通过从其他位置获取相应的数据来重新创建状态。在您的示例中,可能来自某种数据库nosql或sql。

Nothing you do in PHP alone will help you to preserve state across two requests. Your $shoppingCart is created from the scratch for each request, in fact, your whole application is. You should NOT try to persist data in objects instead you should recreate state after every request, by fetching the respective data from somewhere else. In your example probably from some sort of database nosql or sql.

您可以将用户特定的数据持久保存在超全局 $ _ SESSION 中,但在大多数情况下,我建议不要这样做。您的用户会话应保存身份验证和用户数据,但应避免在其中存储与业务逻辑相关的各种数据。

You can persist user specific data in the superglobal $_SESSION, but in most cases I advice against it. Your user session should hold authentication and user data but you should avoid storing all kinds data relevant for your business logic in there.

这篇关于PHP中的Singleton模式。...如何在请求之间保存状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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