User Guide

From struts4php

Jump to: navigation, search

Contents

Why using struts4php

The actual version of the framework was designed for PHP 5 and uses the object oriented features introduced with this PHP version like Interfaces and Iterators.

The framework supports the developer beside it's main function, even controlling the applications flow, implementing I18N, validation of the user data, to pay attention for the system architecture. The framework does not, against many other frameworks, provide functionality for the model (handling the database) or building the GUI part of an application. struts4php only covers the controller part.

This is intended, because as a result of this, the developer is free to use any database layer or template engine, and there are many really good out there, that fits best for the actual requirements. Nearly all would fit perfectly together with the framework. This gives the developer a maximum in flexibility using the best fitting software components.

System requirements

  • Windows or Linux
  • PHP 5.x
  • optional a PEAR installation

Installation

As mentioned above, the framework consists of several packages. This packages have to be inside your applications include path. Therefore the installation can be done in two ways.

PEAR installer

The easier way is to use the PEAR installer if possible. The PEAR installer does all necessary things for you. It downloads packages, extracts them and copies the source files to the PEAR directory on your computer. The PEAR directory is usually in your include path what means that there is nothing more to do.

To install the framework with the PEAR installer it first is necessary to discover the PEAR channel for struts4php. Afterwards the packages can be installed from the newly discovered channel.

Open the commandline and enter the follwing:

root@localhost:~$ pear channel-discover pear.struts4php.org
root@localhost:~$ pear install struts4php/struts4php

After this the framework and all necessary packages were downloaded and installed by the PEAR installer and the framework is ready to use.

Manual installation

The second way is a little bit more tricky, because you have to download all necessary packages manually, extract and copy them to a folder that is in your include path. An advantage of this is, that your application is independent from other applications running on the server, that maybe needs other versions of the framework or other libraries.

The framework depends on the following packages:

  • lang
  • collections
  • logger
  • httputils
  • resources
  • struts4php
  • properties

You can download the latest version of these packages from http://pear.struts4php.org/get.

Controller Components

The ActionController class

Overview

The ActionController class is the main component of the framework. The ActionController has several jobs. First it has to process the users request, what means, that the URL has to be mapped to one of the frameworks Action classes. Then, after successfully handling the request by executing the functionality implemented in the Action, finally the ActionController has to select the view that should be returned to the user.

Using the ActionController

Example:

include_once "httputils/httprequest.php";
include_once "struts4php/action/actioncontroller.php";
 
$controller = new ActionController("WEB-INF/struts-config.xml", "en_US");
$controller->initialize();
include_once($controller->process(HTTPRequest::singleton()));

The example show a very basic usage of the ActionController. The script that contains the source code above could have the name index.php and has to be in the root directory of your web application. In this case all links in your application, that should use the framework have to link to this script.

After invoking the process() method of the controller the framework tries to find a mapping in the configuration file for the path parameter in the request. If a mapping was found, the Action will be instantiated, processed and the path to the view will be returned. In this case, this has also to be a PHP script, that will be included and then render the GUI.

The ActionForm class

Overview

An ActionForm class is a container for the data entered and sent by the user with the request. ActionForm classes provide functionality for automated validation of the data and prefilling the GUI with data gathered by the ActionController while handling the request.

Implementation of an ActionForm

Example for an ActionForm:

include_once "httputils/interfaces/request.php";
include_once "struts4php/action/actionerror.php";
include_once "struts4php/action/actionerrors.php";
include_once "struts4php/action/actionmapping.php";
include_once "struts4php/interfaces/actionform.php";
 
class LoginForm implements ActionForm {
 
    private $username = null;
    private $password = null;    
 
    public function setUsername($username) {
        $this->username = $username;
    }
 
    public function setPassword($password) {
        $this->password = $password;
    }
 
    public function getUsername() {
        return $this->username;
    }
 
    public function getPassword() {
        return $this->password;
    }
 
    /**
     * @see ActionForm::init(Request $request)
     */
    public function init(Request $request) {
        $this->username = $request->getParameter("username");
        $this->password = $request->getParameter("password");
    }
 
    /**
     * @see ActionForm::reset(ActionMapping $actionMapping)
     */
    public function reset(ActionMapping $actionMapping) {
        $this->username = null;
        $this->password = null;
    }
 
    /**
     * @see ActionForm::validate(ActionMapping $actionMapping, Request $request)
     */
    public function validate(ActionMapping $actionMapping, Request $request) {
 
        $errors = new ActionErrors();
 
        if(empty($this->username)) {
            $error = new ActionError("username", "Please enter a username");
            $errors->addActionError($error);
        }
 
        if(empty($this->password)) {
            $error = new ActionError("password", "Please enter a password");
            $errors->addActionError($error);
        }
 
        return $errors;
    }
}

This example demonstrates how to use a ActionForm for validating the input of an user try to login to a web application. The validate() method is invoked automatically by the framework, if configured in the configuration file, and checks if an username and a password was entered by the user.

The ActionForm is used to check if the data entered by the user is valid, e. g. is a valid mail address. This is useful to pass only secured data to the Action. So in the Action you don't have to take care about this but only implement your business logic. Usually an ActionForm does never implement business logic.

The Action class

Overview

The Action class implements the applications flow and achives the functionality provided by the classes and their methods implemented by the developers therefore.

During runtime, if the requested URL maps to a mapping defined in the configuration file, the specified Action is instantiated and the perform() method is invoked. This method has three parameter. The first is the ActionMapping that contains the data specified in the configuration file. The second one holds an instance of the ActionForm, if specified in the configuration file. The framework populates the ActionForm with the data, found in the request, but only if the members fits to the request parameter names.

Example:

my.webapplication.com/index.php?path=/login&username=test&password=test

If the URL above would be send to your webserver, the framework will populate the ActionForm with the values of the parameter username and password. So it is necessary that the input fields in your HTML source code has the same names than the member variables in your ActionForm to let them automatically be populated by the framework. The method, POST or GET, is equal. So the example above can also be send with the POST method.

Implementation of an Action

Example for an Action:

include_once "httputils/interfaces/request.php";
include_once "struts4php/interfaces/action.php";
include_once "struts4php/action/actionerror.php";
include_once "struts4php/action/actionerrors.php";
include_once "struts4php/action/actionmessage.php";
include_once "struts4php/action/actionmessages.php";
include_once "struts4php/action/actionmapping.php";
 
class LoginAction implements Action {
 
    const SUCCESS = "Success";
    const FAILURE = "Failure";
 
    /**
     * @see Action::perform(ActionMapping $actionMapping, ActionForm $actionForm, Request $request)
     */
    function perform(ActionMapping $actionMapping, $actionForm, Request $request) {
 
        $username = $actionForm->getUsername();
        $password = $actionForm->getPassword();
 
        if($username != "test" || $password != "test") {
            $errors = new ActionErrors();
            $errors->addActionError(new ActionError("error", "Invalid user credentials passed"));
            $request->setAttribute(ActionErrors::$ACTION_ERRORS, $errors);
            return $actionMapping->findForward(self::FAILURE);
        } else {
            $messages = new ActionMessages();
            $messages->addActionMessage(new ActionMessage("success", "User successfully logged in"));
            $request->setAttribute(ActionMessages::$ACTION_MESSAGES, $messages);
            return $actionMapping->findForward(self::SUCCESS);
        }
    }
}

This example demonstrates how to implement an Action that validates the username and password from the ActionForm and redirects the framework, depending if the validation was successfull, to the GUI defined in the configuration.

In this example the credentials are validated against fixed strings. In a real web application the username and password would be loaded from a database or a file. As you can see, the Action's perform() method would only be invoked, if the validation of the credentials in the ActionForm was successfull. The Action implements the functionality to load the data from the database or a file and validates it against the one's passed in the ActionForm.

Implementation of a template

Example for a template file:

<?php
 
    include_once "struts4php/action/actionerrors.php";
    include_once "struts4php/action/actionmessages.php";
 
    $actionForm = $_REQUEST["loginForm"];
    $errors = $_REQUEST[ActionErrors::$ACTION_ERRORS];
    $messages = $_REQUEST[ActionMessages::$ACTION_MESSAGES];
 
?>
<html>
    <head><title>Login</title></head>
      <body>
          <?php 
              foreach($errors as $error) { echo $error->getMessage() . '<br/>'; }
              foreach($messages as $message) { echo $message->getMessage() . '<br/>'; } 
          ?>
          <form name="loginForm" method="post" action="index.php">
              <input type="hidden" name="path" value="/login">
              <input type="text" name="username" value="<?php echo $actionForm->getUsername(); ?>"/><br/>
              <input type="text" name="password" value="<?php echo $actionForm->getPassword(); ?>"/><br/>
              <input type="submit" name="Login" value="login"/>
          </form>
     </body>
</html>

This is an example of how a template for the login page can be implemented. Usually there will be separate functions or methods for rendering the errors an messages that will be called from the template.

The HTTPRequest

Overview

The HTTPRequest, passed as parameter to the ActionForm's validate() and to the Action's perform() method, is a wrapper for the global variable $_REQUEST. It is used for transferring data from the users request not only to populate the ActionForm or making it available for the developer in the Action but also to transfer data, gathered in the Action's perform method, from the Action to the GUI. The HTTPRequest also provides several methods for accessing the actual URL including the parameters.

Usage

A reference to the actual HTTPRequest instance used by the framework is passed as parameter to the perform method of each Action.

Example, how to add a value to the HTTPRequest in the perform() method of an Action:

perform(ActionMapping $actionMapping, ActionForm $actionForm, Request $request) {
    // do something here to get the name
    $name = "Foo";
    $request->setAttribute("name", $name);
    return $actionMapping->findForward("Success");
}

Problem with httputils 2.0.3

If you encounter problems like these when playing with the examples mentioned in this guide:

Warning: Invalid argument supplied for foreach() in templates/login.php on line 21
Warning: Invalid argument supplied for foreach() in templates/login.php on line 22

then you need to patch httputils/httprequest.php like this:

--- ../httputils-2.0.3.orig/httprequest.php     2007-06-18 13:58:16.000000000 +0200
+++ httprequest.php     2007-08-16 17:04:12.567525637 +0200
@@ -120,6 +120,7 @@
          */
         public function setAttribute($name, $attribute) {
                        $this->attributes[$name] = $attribute;
+                       $this->toRequest();
         }

         /**
@@ -137,6 +138,7 @@
          */
         public function removeAttribute($name) {
                        unset($this->attributes[$name]);
+                       $this->toRequest();
                }
 
                /**

Configuration

Overview

The framework uses a XML file for configuration. The XML file is usually parsed on every request. The information found in the configuration file, usually named struts-config.xml, will be used to initialize the objects that are necessary to control the applications flow.

Implementation of a configuration file

Example:

<struts-config>
    <form-beans>
        <form-bean name="loginForm" type="LoginForm" include="forms/loginform.php"/> 
    </form-beans>
    <action-mappings>
        <action path="/login" 
                name="loginForm"
                type="LoginAction"
                input="templates/login.php"
                scope="request"
                validate="true"
                include="actions/loginaction.php"
                unknown="true">
            <forward name="Success" path="templates/home.php" />
            <forward name="Failure" path="templates/login.php" />    		
        </action>
    </action-mappings>
</struts-config>

Links

Personal tools