.. _how-to-write-a-command: ###################### How to write a command ###################### All functions specified in the :ref:`backend-api` are defined in command-files located in **src/commands**. They are grouped by their functionality, so all functions related to one section could be disabled by not load the corresponding command file - see :ref:`settings `. In this chapter is described how to write such a command file. .. note:: There is in every code block an " new SmartWFM_Param('string'), 'key2' => new SmartWFM_Param('integer') ) ); /* array * $items is just the containing data type */ $param_test = new SmartWFM_Param( $type = 'array', $items = new SmartWFM_Param('string') ); /* key_data_object (known as associative array) * counterpart of object for dynamic key values. * $items contains two named subelements "key" with the test class for * the keys and "value" for the values. */ $param_test = new SmartWFM_Param( $type = 'key_data_object', $items = array( 'key' => new SmartWFM_Param('string'), 'value' => new SmartWFM_Param('string') ) ); Here is an example to demonstrate the difference between object (upper example) and key_data_object (lower example). The upper example has static names for the keys which are known before runtime. In the lower example the keys are dynamic. .. code-block:: guess Array ( [name] => 'Michael' [age] => 22 ) Array ( ['Michael'] => 22 ['James'] => 45 ) Validation ---------- Now you only have to initiate the tests by use of the following line, where $params is the parameter passed to the *process* method and will be overwritten with the validated parameter: .. code-block:: guess $params = $param_test->validate($params); Exception --------- If the test fails an exception of the type **SmartWFM_Excaption_Params** and with an error message will be thrown. The backend automatically handles this. Logic and exceptions ==================== Now you can write down your logic and process the action. If an error occur just raise an exception like this: .. code-block:: guess throw new SmartWFM_Exception('Your error message here', -1); This includes a message and the error code. The backend catch it and creates the error response. (see :ref:`backend-api-error`) Response ======== Returning the response is really easy. You only need to create a new SmartWFM_Response object, save your response data to it's data variable and return it. Everything else like create it's corresponding JSON string is done by the backend core. .. code-block:: guess $response = new SmartWFM_Response(); $response->data = $yourData; return $response; It is also possible to write this in one line: .. code-block:: guess return new SmartWFM_Response($yourData);