Every Phel file is required to have a namespace. A valid namespace name starts with a letter, followed by any number of letters, numbers, or dashes. Individual parts of the namespace are separated by the
\ character. The last part of the namespace has to match the name of the file.
(ns name imports*)
Defines the namespace for the current file and adds imports to the environment. Imports can either be uses or requires. The keyword
:use is used to import PHP classes and the keyword
require is used to import Phel modules.
(ns my\custom\module (:use Some\Php\Class) (:require my\phel\module))
The call also sets the
*ns* variable to the given namespace.
Before a Phel module can be used, it has to be imported with the keyword
:require. Once imported, the module can be accessed by its name followed by a slash and the name of the public function or value.
Given, a module
util is defined in the namespace
(ns hello-world\util) (def my-name "Phel") (defn greet [name] (print (str "Hello, " name)))
boot imports module
util and uses its functions and values.
(ns hello-world\boot (:require hello-world\util)) (util/greet util/my-name)
To prevent name collision from other modules in different namespaces, aliases can be used.
(ns hello-world\boot (:require hello-world\util :as utilities))
Additionally, it is possible to refer symbols of other modules in the current namespace by using
(ns hello-world\boot (:require hello-world\util :refer [greet])) (greet util/my-name)
:as can be combined in any order.
PHP classes are imported with the keyword
(ns my\custom\module (:use Some\Php\ClassName)
Once imported, a class can be referenced by its name.
To prevent name collision from other classes in different namespaces, aliases can be used.
(ns my\custom\module (:use Some\Php\ClassName :as BetterClassName)
Importing PHP classes is considered a "better" coding style, but it is optional. Any PHP class can be used by typing its namespace with the class name.