Skip to content
Štěpán Svoboda edited this page May 9, 2016 · 4 revisions

Image Store - Example code

This simple example demonstrates how to use ImageStore in a Nette application using Doctrine.

It assumes that you have the Doctrine EntityManager available trough the application DI container.

Entity

<?php

namespace MyApp\Entities;

use Rostenkowski\ImageStore\Entity\ImageEntity;

/** @ORM\Entity */
class MyImageEntity extends ImageEntity
{
	/** @ORM\Id */
	private $id;

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

}

Presenter

<?php

namespace MyApp\Presenters;

use Doctrine\ORM\EntityManager;
use Nette\Application\UI\Presenter;
use Nette\Application\UI\Form;
use Rostenkowski\ImageStore\ImageStorage;

class MyPresenter extends Presenter
{
	/** @var ImageStorage */
	private $images;

	/** @inject @var EntityManager */
    private $em;

    /** @persistent @var integer */
    private $avatar;

	protected function startup()
	{
		$this->images = new ImageStorage(__DIR__ . '/images', __DIR__ . '/cache');
		$this->template->__imageStore = $this->images; // this is important for the image macros
	}

	public function createComponentProfile()
	{
		$form = new Form();
		$form->addUpload('avatar');
		$form->addSubmit('save', 'Save changes');
		$form->onSuccess[] = function($form, $values) {
			$image = new MyImageEntity();
			$this->images->upload($values->avatar, $image);
			$this->em->persist($image);
			$this->avatar = $image->getId();
		};

		return $form;
	}

	public function renderDefault()
	{
		$this->template->avatar = $this->em->find(MyImageEntity::class, $this->avatar);
	}
}

Latte template

<div>
	...
	<img n:crop="$avatar, '64x64'">
	...
</div>
Clone this wiki locally