草庐IT

PHP OOP::在类之间传递 session key

coder 2024-04-18 原文

我正在尝试找出最合适的设计来在 PHP 5.3 中的类之间传递 session key 。

session key 是从第 3 方 API 检索的,我的应用程序进行各种 API 调用,所有这些调用都需要传入此 session key 。

我已经创建了类来保存相关的 API 调用,例如,类 cart 保存的方法在被调用时会触发对 API 的请求,以从 API_GetCart()、API_AddItem() 等调用中返回数据。

我将 session key 存储在单个 cookie(唯一需要的 cookie)中,并且需要使该 cookie 的值可供我几乎所有的类使用。我不能使用数据库或 $_SESSION 来保存 session 数据。第 3 方 API 负责对购物篮内容等进行 session 管理。

当用户第一次访问我的应用程序时,将没有 cookie 值,因此我需要能够将新的 session key 分配给新的 cookie 并传递该值(自从我们仍在处理相同的 HTTP 请求)到其他类。

我的一个想法是创建一个像这样的 session 类,并将 session 抓取/检查代码放在构造函数中。

class Session {
    public $sk;
    function __construct() {
        //code to check if user has sessionkey (sk) in cookie
        //if not, grab new sessionkey from 3rd party API and assign to new cookie
        // $sk = 'abcde12345'; //example $sk value
    }
}

然后在所有 View 页面上,我将实例化一个新的 Session 实例,然后将该对象作为类构造函数的参数或方法参数传递给需要它的每个类(几乎所有都这样做)。

订单摘要.php

$s = new Session;

//$s currently would only hold one variable, $sk = "abcde12345"
//but in the future may hold more info or perform more work

// what is best approach to making the sessionkey 
// available to all classes? arg to constructor or method... or neither :)

$basket = new Basket;
$baskSumm = $basket->getBasketSummary();

$billing = new Billing;
$billSumm = $billing->getBillingSummary();

$delivery = new Delivery;
$delSumm = $delivery->getDeliverySummary();

//code to render as HTML the customer's basket details
//as well as their billing and delivery details 

创建一个 Session 类(实际上只包含一个值)是最好的主意吗?考虑到它可能需要保存更多的值并执行更多的检查,将其作为一个类感觉“正确”。就将该值传递给各个类而言,最好将 Session 对象传递给它们的构造函数,例如

$se = new Session;
$basket = new Basket($se);
$baskSumm = $basket->getBasketSummary();

我是 OOP 的新手,所以非常感谢一些指导。

最佳答案

你可以使用工厂模式。 Basket、Billing 和 Delivery 对象应由第 3 方服务 API 包装类创建:

$svc = new The3rdPartyServiceApiWrapper();
$svc->init();  // connect, get session etc.
if ($svc->fail()) die("halp! error here!");

$basket = $svc->createBasket();
$baskSumm = $basket->getBasketSummary();

$billing = $svc->createBilling();
$billSumm = $billing->getBillingSummary();

$delivery = $svc->createDelivery();
$delSumm = $delivery->getDeliverySummary();

将 Basket、Billing 和 Delivery 类与 API 连接的最佳方法是存储对 API 类的引用,然后它们可以调用它的任何方法,而不仅仅是 getSession()。

另一个优势是,如果您有一个确定的实体,例如一个用户,然后包装类可以授予你,场景中不会有双重对象。

如果主程序创建了用户,那么同一个用户应该有不同的对象,这是错误的:

$user1 = new User("fred12");
$user2 = new User("fred12");

VS 如果 API 包装器创建它们,包装器类应该保留用户的“缓存”,并为相同的请求返回相同的用户对象:

$user1 = $svc->createUser("fred12");
$user2 = $svc->createUser("fred12");  // $user2 will be the same object

(也许这不是一个最好的例子,如果一个程序创建了两次相同的用户,则意味着该程序存在重大设计错误。)

更新: svc 类的解释

The3rdPartyServiceApiWrapper 应该如下所示:

 function getSessionId() {
   return $this->sessionId;  // initialized by constructor
 } // getSessionId()

 function createBasket() {
   $basket = new Basket($this);
   return $basket;
 } // createBasket()

篮子:

 function Basket($s) {  // constructor of Basket class

   $this->svc = $s;

   //... the rest part of constructor

 } // Basket() constructor

function doSomethingUseful() {

  // if you wanna use the session:
  $sess = $this->svc->getSessionId();
  echo("doing useful with session $session");

  // you may access other api functions, I don't know what functions they provide
  $this->svc->closeSession();

} // doSomethingUseful()

关于PHP OOP::在类之间传递 session key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4592081/

有关PHP OOP::在类之间传递 session key的更多相关文章

  1. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  2. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  3. ruby-on-rails - `a ||= b` 和 `a = b if a.nil 之间的区别? - 2

    我正在检查一个Rails项目。在ERubyHTML模板页面上,我看到了这样几行:我不明白为什么不这样写:在这种情况下,||=和ifnil?有什么区别? 最佳答案 在这种特殊情况下没有区别,但可能是出于习惯。每当我看到nil?被使用时,它几乎总是使用不当。在Ruby中,很少有东西在逻辑上是假的,只有文字false和nil是。这意味着像if(!x.nil?)这样的代码几乎总是更好地表示为if(x)除非期望x可能是文字false。我会将其切换为||=false,因为它具有相同的结果,但这在很大程度上取决于偏好。唯一的缺点是赋值会在每次运行

  4. ruby - rails 3 redirect_to 将参数传递给命名路由 - 2

    我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use

  5. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

  6. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  7. [工业相机] 分辨率、精度和公差之间的关系 - 2

    📢博客主页:https://blog.csdn.net/weixin_43197380📢欢迎点赞👍收藏⭐留言📝如有错误敬请指正!📢本文由Loewen丶原创,首发于CSDN,转载注明出处🙉📢现在的付出,都会是一种沉淀,只为让你成为更好的人✨文章预览:一.分辨率(Resolution)1、工业相机的分辨率是如何定义的?2、工业相机的分辨率是如何选择的?二.精度(Accuracy)1、像素精度(PixelAccuracy)2、定位精度和重复定位精度(RepeatPrecision)三.公差(Tolerance)四.课后作业(Post-ClassExercises)视觉行业的初学者,甚至是做了1~2年

  8. ruby - 如何将 Puma::Configuration 传递给 Sinatra? - 2

    这是我的网络应用:classFront我是这样开始的(请不要建议使用Rack):Front.start!这是我的Puma配置对象,我不知道如何传递给它:require'puma/configuration'Puma::Configuration.new({log_requests:true,debug:true})说真的,怎么样? 最佳答案 配置与您运行的方式紧密相关puma服务器。运行的标准方式puma-pumaCLI命令。为了配置puma配置文件config/puma.rb或config/puma/.rb应该提供(参见examp

  9. ruby - 为什么在类上调用 instance_eval() 时定义类方法? - 2

    Foo=Class.newFoo.instance_evaldodefinstance_bar"instance_bar"endendputsFoo.instance_bar#=>"instance_bar"putsFoo.new.instance_bar#=>undefinedmethod‘instance_bar’我的理解是调用instance_eval在对象上应该允许您为该对象定义实例变量或方法。但是在上面的例子中,当你在类Foo上调用它来定义instance_bar方法时,instance_bar变成了一个可以用“Foo.instance_bar”调用的类方法。很明显这段代码没

  10. jquery - 如何将 AJAX 变量从 jQuery 传递到他们的 Controller ? - 2

    我有一个电子邮件表格。但是我正在制作一个测试电子邮件表单,用户可以在其中添加一个唯一的电子邮件,并让电子邮件测试将其发送到该特定电子邮件。为了简单起见,我决定让测试电子邮件通过ajax执行,并将整个内容粘贴到另一个电子邮件表单中。我不知道如何将变量从我的HAML发送到我的Controllernew.html.haml-form_tagadmin_email_blast_pathdoSubject%br=text_field_tag'subject',:class=>"mass_email_subject"%brBody%br=text_area_tag'message','',:nam

随机推荐