Tuesday, March 12, 2013

zf2 howto GridFS

GridFS is the mongoDB standard for storing and retrieving files.You can find out more information about GridFS here.

This is how I managed to store and retrieve image using zf2, doctrine-odm and mongoDB.

You can setup a Document,

<?php
namespace Course\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/** @ODM\Document(collection="course") */
class Course
{
    /** @ODM\Id */
    private $id;

    /** @ODM\File */
    private $thumb;


    public function getId() {
        return $this->id;
    }

    public function getThumb()
    {
        return $this->thumb;
    }

    public function setId($id) {
        $this->id = $id;
    }

     public function setThumb($thumb)
    {
        $this->thumb = $thumb;
    }

    public function exchangeArray($data)
    {
        $this->id               = (isset($data['id']))     ? $data['id']     : null;
        $this->thumb            = (isset($data['thumb'])) ? $data['thumb'] : null;

    }

   public function getArrayCopy()
    {
        return get_object_vars($this);
    }

    public function getObjectAsArray()
    {
        $array = array(
         'thumb' =>$this->thumb,
                      );
        return $array;
    }

}

Then zf2 form with file upload input field, within your function __construct you can add,



$this->setAttribute('method', 'post');
$this->setAttribute('enctype','multipart/form-data');
$this->add(array(
            'name' => 'id',
            'attributes' => array(
                'type'  => 'hidden',
            ),
        ));
$this->add(array(
            'name' => 'thumb',
            'attributes' => array(
                'type'  => 'file',
            ),
            'options' => array(
                'label' => 'Thumbnail',
            ),
        ));

Then create the form,

<?php
$title = 'upload Image';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('image', array('action' => 'add')));
$form->prepare();

echo $this->form()->openTag($form);
echo $this->formRow($form->get('thumb'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
?>
and finally update your controller with,
$request = $this->getRequest();
        if ($request->isPost()) {

            $data = array_merge_recursive(
            $this->getRequest()->getPost()->toArray(),
            $this->getRequest()->getFiles()->toArray()
             );


     $file_src   = '/tmp/'.$data['thumb']['name'];
         move_uploaded_file($data['thumb']['tmp_name'], $file_src);


    $dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
    $course = new Course();
    $course->setThumb($file_src);
    $dm->persist($course);
        $dm->flush();

    }

To retrieve image, update controller with
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
        $courses = $dm->createQueryBuilder('Course\Document\Course')
                ->getQuery()
                ->execute();

        return new ViewModel(array(
           'courses' => $courses,
        ));
And your view,
<table class="table">
<tr>
    <th>thumb</th>
    <th>&nbsp;</th>
</tr>
<?php foreach ($courses as $course) : ?>
<tr>
    <td><?php $i= base64_encode($course->getThumb()->getBytes());echo "<img src=\"data:image/jpg;base64,{$i}\">";?></td>
</tr>
<?php endforeach; ?>
</table>

 Make sure you set the correct header image type in order to render the image.

further info :
Storing Files with MongoGridFS
ZF2 form collections

No comments:

Post a Comment