3

I have just started with Zend Framework, so I have lots of questions about the structure. I hope I can explain it properly, it's rather difficult.

Ok, I have done the Quickstart Tutorial and decided to use a similar structure for my first project.

So I have a Datamapper, a Model and the Database Table File.

I have created a Form where I can enter a some Information(Item) and upload Images with it.

I have 2 Datamapper (Item and Image) as well as 2 Models for them. I have an Item Controller, that one jumps into the ItemMapper. In the Datamapper I have a save Method. Please see below:

 public function save(Application_Model_Item $item)
{

    $data = array(
           'item_title'        => $item->getItemTitle(),
           'item_description'  => $item->getItemDescription(),
            );
    $this->getDbTable()->insert($data);

    // Add Image Information ($imageData is Session Data) 
    $table  = new Application_Model_DbTable_Image();
    foreach ($imageData as $fileData)
    { 
        $image = new Application_Model_Image($fileData);
        $data = array(  
              'image_newname'   => $image->getNewImageName(),
              'image_thumbname' => $image->getImageThumbName(),      
            );
        $table->insert($data);
     }

Now the question I have.

  1. I have Getter and Setter in my Model. Should everything what is in the Item Database Table be in 1 Model? Means everything about the Image should go to the Image Model since it is in a different Database Table?
  2. Is it correct that I save the Information about the Image in the Item Mapper? Shoudl I not have a save() Method in the ImageMapper and save it in there? If so, how do I jump from the Item Mapper to the Image Mapper? Or would I first finish everything about the Item, return the ID to the Controller and than call the ImageMapper from the Controller?
  3. I read something about "Fat Model Thin Controller". I had this all the time in my had, but I noticed that my Controller got pretty fat with just putting the Form together. I have about 5 Dropdown Fields which are depending Dropdowns. When I saw that I duplicating Code I decided to add this in a separate Function. So f.e. I have a Dropdown for counties. I wrote a Function which is also in my Controller so it looks like this:

    public function getCounties ()
    

    {

    // List of Counties does not exist in Cache, read from DB
        if(!$CountyList = $this->getFromCache('counties')){
    
        $geolocationMapper = new Application_Model_GeolocationMapper();
        $CountyDropdown = $geolocationMapper->createCountyDropdown();
    
        // Save DB Result in Cache
        $this->addToCache ('counties',$CountyDropdown);
        return $CountyDropdown;
    }
    else{
        // Return Country List from Cache
        return $this->getFromCache('counties');            
    }   
    

    }

In my Add Function I use

// Assign Geo Info to Form

$CountyList = $this->getCounties();               
$form->getElement('county')->setMultiOptions($CountyList);   

The Edit Function than

$CountyList = $this->getCounties();
$form->getElement('county')->setMultiOptions($CountyList)->setValue($activeCounty)

all the Functions like getCounties () stay in the Controller or should it be moved to the GeolocationMapper? And if so, how would that be called up?

  1. Should the Form be created in some Function so I would only call up something like createForm() ? I really have a lot of duplication (Add and Edit Function) and than Stuff comes from Database or Form was not Valid and it comes from Cache with a setValue. It just adds up when using dependable Dropdowns.

I know this are lots of questions, but I have the feeling it gets very messy, as a learner you are happy when it works, but I would also like to structure it in a proper way. I hope it all makes sense.

Maybe some of you have a few Tipps I could use. Thanks a lot for your help in advance.

2
  • This seems more like a discussion. Perhaps it should be migrated to programmers.stackexchange.com Commented Jul 21, 2011 at 14:23
  • Zend Framework is about OOP plus MVC and I sense that you are not familiar with both. Reminds me of my bumpy start with ZF. I literary threw away ZF for a few weeks and read books about OOP and MVC. Once you have that down the Framework is a breeze. Commented Jul 21, 2011 at 15:42

2 Answers 2

1

There are quite a few questions here and most of the answers will be down largely to personal preference. With that caveat out of the way:

Should everything what is in the Item Database Table be in 1 Model?

I would say yes, although in general, try and think about it from the perspective of the models rather than the database structure. So all of the 'item' data goes in the Item model - the fact that this is all stored in one database table is irrelevant, since the mapper handles the translation from one to the other.

Is it correct that I save the Information about the Image in the Item Mapper?

It's not clear where $imageData comes from in your example, but I'd say the Item mapper should call the Image mapper if there is image data to save, e.g.:

public function save(Application_Model_Item $item)
{
    $data = array(
        'item_title'        => $item->getItemTitle(),
        'item_description'  => $item->getItemDescription(),
    );
    $this->getDbTable()->insert($data);

    // save image data if present
    if (isset($item->image)) {
        $imageMapper = new Yourapp_Mapper_Image();
        $imageMapper->save($item->image);
    }

    return true;
}

[Should] all the Functions like getCounties () stay in the Controller or should it be moved to the GeolocationMapper? And if so, how would that be called up?

I don't see any reason for these functions to be in the controller. Depending on how comfortable you are with the Zend_Form component, one approach might be to write a custom Yourapp_Form_Element_Counties class that extends Zend_Form_Element_Select. You then move your logic from the getCounties function into the this class, so the form element itself is responsible for populating the options it presents. E.g.:

class Yourapp_Form_Element_Counties extends Zend_Form_Element_Select
{
    public function getMultiOptions()
    {
        // load counties here and return an array in the format key -> value
    }
}

Another approach, if you have a lot of location-related form elements, might be to create a GeoLocation Service class, which has a function for counties, cities etc. that returns the options.

Should the Form be created in some Function so I would only call up something like createForm()

It's not clear how much form stuff you are doing in the controller already apart from populating select options, so it's hard to answer this one. Here are the principles I generally follow when using Zend_Form:

  • Each form has its own class, extending Zend_Form (or Zend_Dojo_Form), which exists in application/forms and is named Myapp_Form_*
  • Each form class sets up its elements in the init() method (which is called automatically by Zend_Form's constructor for exactly this purpose).
  • If I find I need slight variations to the same form in different actions (e.g. in an add and edit action), I create an abstract base class for the form (e.g. Myapp_Form_Post_Base) which defines the elements, and then action-specific classes which extend it: Myapp_Form_Post_Add, Myapp_Form_Post_Edit and so on. These classes make any changes they need to the base form in their own init() method.

My actions then look something like this:

public function editAction()
{
    $form = new Myapp_Form_Post_Edit();

    if ($this->_request->isPost()) {
        if ($form->isValid($this->_request->getPost()) {
            // save data, set flash messge and redirect
        }
    }

    $this->view->form = $form;
}

My only other piece of advice is to try and follow the approach which seems most logical to you. You might find it difficult to find definitive 'best practices' for a lot of this stuff since there are many different ways to do it all.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Tim, thanks a lot for your great explanation. I had to read it a few times, to understand everything specially the part "to write a custom Yourapp_Form_Element_Counties" did not sink in yet, but I guess this is normal when you start with ZF. Just one more time about Q2, which is not fully clear yet. Should the actuall call to save the Imgae be done from the ItemMapper? Means I would call the save() Method of the ImageMapper from inside the save() Method of the ItemMapper? Or return the ItemID to my Controller, than call the ImageMapper from the Controller where I hand over the ItemID? Luka
I've edited my answer with examples of both parts. For the forms stuff, it would be easier for me to show you how to slot this into your app if you could add some code showing how you are creating your forms currently. But this stuff does take a bit of getting your head round.
0

I have tried to follow your ideas as much as possible, so all the calls for the Counties, Towns and Postcodes are in the GeolocationMapper and the saving of the Image Data is in the ImageMapper.

You asked of how I create my Form right now, here an example from my init() of the Form for the Counties etc...

  // Create Dropdown for Counties          
    $county = new Zend_Form_Element_Select('county');      
    $county->setLabel('Select a County')
           ->setRegisterInArrayValidator(false) 
       ->setDecorators(array(
        'ViewHelper',
        'Errors',
              array('Description', 
                      array('tag' => 'p', 'class'=>'description')),         
                    'Label',
              array('HtmlTag',
              array('tag'=>'li','class'=>'county'))                 
             ))  
           ->setRequired(false);

    // Create Dropdown for Town
    $town = new Zend_Form_Element_Select('town');
    $town->setRegisterInArrayValidator(false)
         ->setDecorators(array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('tag' => 'p', 'class' => 'description')),
                            'Label',
                            array('HtmlTag',array('tag'=>'li','class'=>'town'))
                            ));  


    // Create Dropdown for Postcode
    $postcode = new Zend_Form_Element_Select('postcode');
    $postcode->setRegisterInArrayValidator(false)
             ->setDecorators(array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('tag' => 'p', 'class' => 'description')),
                            'Label',
                            array('HtmlTag',array('tag'=>'li','class'=>'postcode'))
                            )) 
             ->setRegisterInArrayValidator(false);

In my Controller I than get the Elements and fill them:

$geolocationMapper = new Application_Model_GeolocationMapper();
$CountyOptions = $geolocationMapper->createCountyDropdown();
$form->getElement('county')->setMultiOptions($CountyOptions);

In my GeolocationMapper I have the Methods to build my Array of Counties:

/** ===========================================================================
* Get Counties
* @param 
* @return Object? of Counties  
* ========================================================================= */   

public function getCountyList()
{
        $table = $this->getDbTable();

        $select = $table->select()->distinct()
                  ->from(array('p' => 'geolocation'),'county')
                  ->order('county');
        $resultSet = $this->getDbTable()->fetchAll($select);
        $entries   = array();
        foreach ($resultSet as $row)
        {
            $entry = new Application_Model_Geolocation();
            $entry->setId($row->county)
                  ->setCounty($row->county);   
            $entries[] = $entry;
        }
        return $entries;    
}     



/** ===========================================================================
* Create Array which will be used for Dropdown
* @param 
* @return Array of Counties  
* ========================================================================= */   

public function createCountyDropdown()
{

    // List of Counties does not exist in Cache, read from DB
    if(!$CountyList = $this->getFromCache('counties'))
    {               
        $CountyList = $this->getCountyList();
        $Counties[''] = "Please choose";

        foreach($CountyList as $value)
        {
             $Counties[str_replace(' ','_',$value->getCounty())] = $value->getCounty();
        }

        $CountyDropdown = $Counties;

        // Save DB Result in Cache
        $this->addToCache ('counties',$CountyDropdown);
        return $CountyDropdown;

    }else{
        return $this->getFromCache('counties');     
    }

}

The Counties I read in my GeolocationMapper. The Towns and Postcodes get read when you choose a County, which than calls via Ajax the Geolocation Mapper and than createTownDropdown($county) and when a Town is choosen the same procedure but an Ajax call for loadPostcodes() and there createPostcodeDropdown($town).

Does this all sounds correct or any suggestions how I could improve this?

I am sorry but I would really like to add another question since I can't find an answer anywhere... I also have an Image Upload which works via Ajax and jQuery. When you choose an Image to upload, the Image gets straight displayed. For this I create dynamically an input Element with an image src. I have not found ny other way to add Images otherwise to Zend Form. Is there a possibility to add an Image to display the image as a normal ? It would be just a lot easier to have a img, since I would like to use jQuery Drag and Drop. Thanks so much for your help so far !!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.