drvonr6573 2016-10-20 15:01
浏览 64
已采纳

PHP - SLIM API - 如何跨多个PHP文件共享变量,但请求具体

I have a server running a API using Slim.

Each API request points to PHP code / functions divided in different PHP files. I'm not so heavy into PHP, and now I'm passing or setting variables in each class where needed.

I'm Wondering if there isn't a better way to set a REQUEST SCOPE 'global' variable that can be shared across the different PHP files? But are not shared between all the incoming request.

Should I:

  • Work with Sessions?
  • Work with a Singleton?
  • ...

Code examples are difficult to give. This question fits more into a conceptual question.

Any good advice into accomplishing the sharing of variables across multiple PHP files, but with the REQUEST scope?

  • 写回答

1条回答 默认 最新

  • dongxueji2838 2016-10-20 15:13
    关注

    You should understand that your PHP application is initiated for each incoming request, so there is no way you can "share" data between requests accidentaly. I now cannot think of a way to do it on purpose, really.

    As for "sharing information" between different files: the information is actually shared. Here's an example:

    project/
        test.php
        mew.php
    

    Content of test.php:

    <?php
    $foo = 'bar';
    include 'mew.php';
    

    Content of mew.php:

    <?php
    echo $foo; // accessing variable that was declared in "parent" file
    

    Output of GET project/test.php request:

    bar
    

    So, you don't really have "sharing" problem.

    Edit

    From your comment I understand that you need some sort of client authentication. This can be done in many ways: from primitive and insecure authentication by IP address (using this middleware, for instance), classy HTTP authentication (tool for that), JWT is a good method (tool).

    Conceptually it is simple: every client's request must be followed with some sort of token. When you recieve a request, you grab that token, identify client by it and return appropriate response.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型