Last Updated: February 25, 2016
· francescoagati

writing code for slim framework in lisp

We can use pharen macro for write better dry code.

This are macro example for slim framework:

(defmacro slim-init () '(def app (new Slim)))
(defmacro slim-set-local-instance () '(local app (:: Slim (getInstance))))

(defmacro slim-http-request (method route name args &body)
   (-> app (~method ~route ~name) (name ~name))
    (fn ~-name ~args  
      (local app (:: Slim (getInstance)))
      (local params (slim-params))

(defmacro slim-rq-is (cond &body)
  (def method-name (. "is" cond))
  '(if (-> (slim-rq) (~method-name)) ~@body FALSE)

(defmacro slim-response-with-json (data)
  '(-> app (response) (body (json-encode ~data))))

(defmacro slim-get (route name args &body) '(slim-http-request get ~route ~name ~args ~@body))
(defmacro slim-post (route name args &body) '(slim-http-request post ~route ~name ~args ~@body))
(defmacro slim-put (route name args &body) '(slim-http-request put ~route ~name ~args ~@body))
(defmacro slim-delete (route name args &body) '(slim-http-request delete ~route ~name ~args ~@body))

(fn slim-rq () 
  (-> app request))

(fn slim-params () (-> (slim-rq) (params)))

and an example of use

(require-once #slim.php)

(def n 123)

(slim-get "/books/:one/:two" #get-book (one two) 

  (echo n)
  (echo (-> (slim-rq) (params #ciccio )))
  (slim-rq-is #get 
    (echo "get"))

  (slim-rq-is #Ajax 
  (slim-response-with-json [(dict #a 1) (dict #a 2)]))

  (echo (. "first parameter" one))
  (echo (. "second parameter" two)))