如何避免没有全局变量的lua中的循环依赖? [英] How to avoid circular dependency in lua without global variables?

查看:191
本文介绍了如何避免没有全局变量的lua中的循环依赖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用OpenResty,并且我的应用设置为:

I'm using OpenResty and my app is setup as:

app/
   clients/
      photoClient.lua
   init.lua
   auth.lua

假设photoClient同时具有未经身份验证的端点和经过身份验证的端点(类似于无需登录即可访问的头像端点,但可能需要先登录私人照片)

Let's say photoClient has both an unauthenticated and a authenticated endpoint (similar to an avatar endpoint that is accessible without logging in, but there may be private photos that you need to login first)

因此,关于依赖项,我有:

So in terms of dependencies, I have:

-- auth.lua

local photoClient = require('app.clients.photoClient')
-- this is used to show avatar on the login page

local auth = {}

auth.isAuthenticated = function ()
   -- logic to check authentication
end

return auth

客户是

-- photoClient.lua
local auth = require('app.auth')

local photoClient = {}
photoClient.privateEndpoint = function()
   if (!auth.isAuthenticated()) {
       ngx.exit(403)
   }
   ...
end

photoClient.getAvator = function() {
   -- this is a public method used by auth
}

return photoClient

这给了我一个循环依赖的问题.我在其他SO帖子上看到可以使用全局变量,即做photoClient = photoClient or require('app.clients.photoClient'),但是我不想使用全局变量,并且不想让每个模块都局限于自身.

This is giving me a circular dependency issue. I've seen on other SO post that you can use global variables, i.e. to do photoClient = photoClient or require('app.clients.photoClient') but I do not want to use global variables and want to keep each module scoped to itself.

我该怎么做?

推荐答案

在凯特·亚当斯(Kate Adams)的LuaFlare文档上找到了解决方案:在对每个文件执行return your_module之前,基本上先添加package.loaded[...] = your_module,即

Found the solution on LuaFlare Documentation by Kate Adams: basically add package.loaded[...] = your_module before you do return your_module to every file, i.e.

-- auth.lua
local auth = {}
package.loaded[...] = auth

local photoClient = require('app.clients.photoClient')

...

return auth


-- photoClient.lua
local photoClient = {}
package.loaded[...] = photoClient

local auth = require('app.auth')

...

return photoClient

解决了问题.

Fixed the problem. Here is the link to the book's page for anyone who is interested to read more.

这篇关于如何避免没有全局变量的lua中的循环依赖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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