4

作为一个 Clojure 学习练习,我将 Bulbs ( http://bulbflow.com )(我编写的一个图形数据库库)从 Python 移植到 Clojure。

我仍然有些模糊的一件事是如何以 Clojure 惯用的方式构建库。

为了支持多个数据库,Bulbs 使用依赖注入。不同的数据库后端在实现接口的自定义客户端类中抽象出来,客户端在运行时进行配置。

Graph 对象及其各种代理对象包含一个低级 Client 对象的实例:

# bulbs/neo4jserver/graph.py

class Graph(object):

    default_uri = NEO4J_URI

    def __init__(self, config=None):
        self.config = config or Config(self.default_uri)
        self.client = Neo4jClient(self.config)

        self.vertices = VertexProxy(Vertex, self.client)
        self.edges = EdgeProxy(Edge, self.client)

您可以通过为相应的图形数据库服务器创建 Graph 对象来使用 Bulbs:

>>> from bulbs.neo4jserver import Graph
>>> g = Graph()

然后您可以通过代理对象在数据库中创建顶点和边:

>>> james = g.vertices.create(name="James")
>>> julie = g.vertices.create(name="Julie")
>>> g.edges.create(james, "knows", julie)

这种设计使得使用 REPL 中的 Bulb 变得很容易,因为您所要做的就是导入和实例化 Graph 对象(或者如果需要也可以传入自定义的 Config 对象)。

但我不确定如何在 Clojure 中处理这种设计,因为 Graph 对象及其代理需要保存在运行时配置的 Client 对象。

这样做的 Clojure 方式是什么?

更新:这就是我最终做的......

;; bulbs/neo4jserver/client.clj

(def ^:dynamic *config* default-config)

(defn set-config!
  [config]
  (alter-var-root #'*config* (fn [_] (merge default-config config))))

(defn neo4j-client
  [& [config]]
  (set-config! config))

(neo4j-client {:root_uri "http://localhost:7474/data/db/"})

(println *config*)

更新 2:

Andrew Cooke 指出,使用全局变量会阻止您在程序中使用多个独立的图形“实例”,而在 Python 版本中则可以。

所以我想出了这个:

(defn graph
  [& [config]]
  (let [config (get-config config)]
    (fn [func & args]
      (apply func config args))))

(defn create-vertex
  [config data]
  (let [path (build-path vertex-path)
        params (remove-null-values data)]
    (rest/post config path params)))

(defn gremlin
  [config script & [params]]
  (rest/post config gremlin-path {:script script :params params}))

然后你可以像这样调用不同的函数:

(def g (graph {:root_uri "http://localhost:7474/data/db/"}))

(g create-vertex {:name "James"})

(g gremlin "g.v(id)" {:id 178})

现在我还没有深入研究宏,与其他方法相比,我不太确定这种方法的优点,因此欢迎反馈。

4

1 回答 1

6

协议在 Clojure 中非常适合这一点,你定义一个协议(很像一个接口),它定义了与数据库接口所需的所有功能,然后在运行时调用在协议实例中构建的图形协议的构造函数连接到您选择的数据库。

基本流程非常相似,除了使用 Clojure 协议。

于 2012-05-10T20:22:23.357 回答