Last active
July 31, 2019 13:37
-
-
Save goroba/c915afab5a5f0e5016b19af0f687d286 to your computer and use it in GitHub Desktop.
Using UUID as identifier for SonataMediaBundle media entity. File path generates in `/context/year-month/day/filename.ext ` way.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Entity; | |
use Doctrine\ORM\Mapping as ORM; | |
use Sonata\MediaBundle\Entity\BaseMedia as BaseMedia; | |
/** | |
* @ORM\Entity(repositoryClass="App\Repository\MediaRepository") | |
*/ | |
class Media extends BaseMedia | |
{ | |
/** | |
* @ORM\Id | |
* @ORM\Column(name="id", type="guid") | |
* @ORM\GeneratedValue(strategy="UUID") | |
*/ | |
protected $id; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
providers: | |
file: | |
generator: 'App\Bundles\Sonata\MediaBundle\Generator\UuidGenerator' | |
image: | |
generator: 'App\Bundles\Sonata\MediaBundle\Generator\UuidGenerator' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Bundles\Sonata\MediaBundle\Generator; | |
use Ramsey\Uuid\Uuid; | |
use Sonata\MediaBundle\Model\MediaInterface; | |
use Sonata\MediaBundle\Generator\GeneratorInterface; | |
class UuidGenerator implements GeneratorInterface | |
{ | |
/** | |
* {@inheritdoc} | |
*/ | |
public function generatePath(MediaInterface $media) | |
{ | |
$uuid = Uuid::fromString($media->getId()); | |
/** | |
* You can also wrap levels with somthing linke md5() to | |
* encode date in path for end-users. | |
*/ | |
$rep_first_level = ($uuid->getDateTime()->format('Y-m')); | |
$rep_second_level = ($uuid->getDateTime()->format('d')); | |
return sprintf('%s/%s/%s', $media->getContext(), $rep_first_level, $rep_second_level); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment