dongsuoying9059 2016-02-27 12:46
浏览 170
已采纳

拥有Laravel中所有页面的常量

I want to have some constants to have IP, platform, browser to be placed in a single file and to be used in all views and controllers like so:

// inside app/config/constants.php

return [
    'IP' => 'some ip'
];

// inside controller

echo Config::get('constants.IP');

But instead of 'some ip', I want to use Request::ip() at least or even better, to use parse_user_agent()['platform'] that its code link is here

  • 写回答

2条回答 默认 最新

  • dongyu4908 2016-02-27 13:29
    关注

    Simply you may put something like this in your config file:

    return [
        'ip' => app('request')->ip()
    ];
    

    I use a little customized one for my sitewise configs, for example, let's say you want to use something like this:

    /**
     * Get config/constants.php
     *
     * [
     * 'person' => [
     *     'name' => 'Me',
     *     'age' => 1000
     *   ]
     * ];
     */
    $name = constants('person.name');
    

    So, to achieve this you need to write a function like:

    // Helpers/Common.php
    function constants($key = null)
    {
        $constants = config('constants');
        return is_null($key) ? $constants : array_get($constants, $key);
    }
    

    Now, in your composer.json file you may add the following files entry:

    "psr-4": {
            "App\\": "app/"
     },
     "files": ["Helpers/Common.php"]
    

    Then you need to add the constants.php in config directory for example:

    <?php
    
    return [
        "ip" => app('request')->ip(),
        "person" => [
            "name" => "Sheikh Heera",
            "age" => 10000
        ],
    ];
    

    Finally, just run composer-dump from terminal and you are done. So, if the ip key is available in the array then you may just try this:

    $ip = constants('ip');
    

    From the view (Blade), you may use following to echo out the ip:

    {{ constants('ip') }}
    

    Let's sum up the whole process:

    • Create a directory in your project root (or inside app if you wish) as Helpers.

    • Create the Common.php file in that directory and put the array (return it)

    • Put the constants function (given above) in the Common.php file

    • Add the files (given above) key in your composer.json file

    • Run composer-dump to update autoload files

    That's it. Use the file name and helper function name that describes your domian, so instead of constants you may use for example: site or your domain name as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM