PageRenderTime 49ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/examples.rst

http://github.com/josegonzalez/upload
ReStructuredText | 323 lines | 262 code | 61 blank | 0 comment | 0 complexity | 84e88997f30a3637b4bd9fae6f0d7025 MD5 | raw file
  1. Examples
  2. ========
  3. Basic example
  4. -------------
  5. Note: You may want to define the Upload behavior *before* the core
  6. Translate Behavior as they have been known to conflict with each
  7. other.
  8. .. code:: sql
  9. CREATE table users (
  10. id int(10) unsigned NOT NULL auto_increment,
  11. username varchar(20) NOT NULL,
  12. photo varchar(255)
  13. );
  14. .. code:: php
  15. <?php
  16. /*
  17. In the present example, these changes would be made in:
  18. src/Model/Table/UsersTable.php
  19. */
  20. declare(strict_types=1);
  21. namespace App\Model\Table;
  22. use Cake\ORM\Table;
  23. class UsersTable extends Table
  24. {
  25. public function initialize(array $config): void
  26. {
  27. $this->setTable('users');
  28. $this->setDisplayField('username');
  29. $this->setPrimaryKey('id');
  30. $this->addBehavior('Josegonzalez/Upload.Upload', [
  31. // You can configure as many upload fields as possible,
  32. // where the pattern is `field` => `config`
  33. //
  34. // Keep in mind that while this plugin does not have any limits in terms of
  35. // number of files uploaded per request, you should keep this down in order
  36. // to decrease the ability of your users to block other requests.
  37. 'photo' => [],
  38. ]);
  39. }
  40. }
  41. ?>
  42. .. code:: php
  43. <?php
  44. /*
  45. In the present example, these changes would be made in:
  46. templates/Users/add.php
  47. templates/Users/edit.php
  48. */
  49. ?>
  50. <?= $this->Form->create($user, ['type' => 'file']); ?>
  51. <?= $this->Form->control('username'); ?>
  52. <?= $this->Form->control('photo', ['type' => 'file']); ?>
  53. <?= $this->Form->end(); ?>
  54. Note: If you used *bake* to generate MVC structure after creating
  55. the users table, you will need to remove the default scalar validation
  56. for the photos field.
  57. .. code:: php
  58. public function validationDefault(Validator $validator): void
  59. {
  60. $validator
  61. ->integer('id')
  62. ->allowEmptyString('id', 'create');
  63. $validator
  64. ->scalar('username')
  65. ->allowEmptyString('username');
  66. $validator
  67. // remove ->scalar('photo')
  68. ->allowEmptyFile('photo');
  69. return $validator;
  70. }
  71. ?>
  72. Deleting files
  73. --------------
  74. Using the setup from the previous example, uploaded files can only be deleted as long as the path is configured to use
  75. static tokens. As soon as dynamic tokens are incorporated, like for example ``{day}``, the generated path will change
  76. over time, and files cannot be deleted anymore at a later point.
  77. In order to prevent such situations, a field must be added to store the directory of the file as follows:
  78. .. code:: sql
  79. CREATE table users (
  80. `id` int(10) unsigned NOT NULL auto_increment,
  81. `username` varchar(20) NOT NULL,
  82. `photo` varchar(255) DEFAULT NULL,
  83. `photo_dir` varchar(255) DEFAULT NULL,
  84. PRIMARY KEY (`id`)
  85. );
  86. .. code:: php
  87. <?php
  88. /*
  89. In the present example, these changes would be made in:
  90. src/Model/Table/UsersTable.php
  91. */
  92. declare(strict_types=1);
  93. namespace App\Model\Table;
  94. use Cake\ORM\Table;
  95. class UsersTable extends Table
  96. {
  97. public function initialize(array $config): void
  98. {
  99. $this->setTable('users');
  100. $this->setDisplayField('username');
  101. $this->setPrimaryKey('id');
  102. $this->addBehavior('Josegonzalez/Upload.Upload', [
  103. 'photo' => [
  104. 'fields' => [
  105. // if these fields or their defaults exist
  106. // the values will be set.
  107. 'dir' => 'photo_dir', // defaults to `dir`
  108. 'size' => 'photo_size', // defaults to `size`
  109. 'type' => 'photo_type', // defaults to `type`
  110. ],
  111. ],
  112. ]);
  113. }
  114. }
  115. ?>
  116. .. code:: php
  117. <?php
  118. /*
  119. In the present example, these changes would be made in:
  120. templates/Users/add.php
  121. templates/Users/edit.php
  122. */
  123. ?>
  124. <?= $this->Form->create($user, ['type' => 'file']); ?>
  125. <?= $this->Form->control('username'); ?>
  126. <?= $this->Form->control('photo', ['type' => 'file']); ?>
  127. <?= $this->Form->end(); ?>
  128. Using such a setup, the behavior will use the stored path value instead of generating the path dynamically when deleting
  129. files.
  130. Advanced example
  131. ----------------
  132. In this example we'll cover:
  133. - custom database fields
  134. - a nameCallback which makes the filename lowercase only
  135. - a custom transformer where we generate a thumbnail of the uploaded image
  136. - delete the related files when the database record gets deleted
  137. - a deleteCallback to ensure the generated thumbnail gets removed together with the original
  138. This example uses the Imagine library. It can be installed through composer:
  139. .. code::
  140. composer require imagine/imagine
  141. .. code:: sql
  142. CREATE table users (
  143. id int(10) unsigned NOT NULL auto_increment,
  144. username varchar(20) NOT NULL,
  145. photo varchar(255),
  146. photo_dir varchar(255),
  147. photo_size int(11),
  148. photo_type varchar(255)
  149. );
  150. .. code:: php
  151. <?php
  152. /*
  153. In the present example, these changes would be made in:
  154. src/Model/Table/UsersTable.php
  155. */
  156. declare(strict_types=1);
  157. namespace App\Model\Table;
  158. use Cake\ORM\Table;
  159. class UsersTable extends Table
  160. {
  161. public function initialize(array $config): void
  162. {
  163. $this->setTable('users');
  164. $this->setDisplayField('username');
  165. $this->setPrimaryKey('id');
  166. $this->addBehavior('Josegonzalez/Upload.Upload', [
  167. 'photo' => [
  168. 'fields' => [
  169. 'dir' => 'photo_dir',
  170. 'size' => 'photo_size',
  171. 'type' => 'photo_type',
  172. ],
  173. 'nameCallback' => function ($table, $entity, $data, $field, $settings) {
  174. return strtolower($data->getClientFilename());
  175. },
  176. 'transformer' => function ($table, $entity, $data, $field, $settings, $filename) {
  177. $extension = pathinfo($filename, PATHINFO_EXTENSION);
  178. // Store the thumbnail in a temporary file
  179. $tmp = tempnam(sys_get_temp_dir(), 'upload') . '.' . $extension;
  180. // Use the Imagine library to DO THE THING
  181. $size = new \Imagine\Image\Box(40, 40);
  182. $mode = \Imagine\Image\ImageInterface::THUMBNAIL_INSET;
  183. $imagine = new \Imagine\Gd\Imagine();
  184. // Save that modified file to our temp file
  185. $imagine->open($data->getStream()->getMetadata('uri'))
  186. ->thumbnail($size, $mode)
  187. ->save($tmp);
  188. // Now return the original *and* the thumbnail
  189. return [
  190. $data->getStream()->getMetadata('uri') => $filename,
  191. $tmp => 'thumbnail-' . $filename,
  192. ];
  193. },
  194. 'deleteCallback' => function ($path, $entity, $field, $settings) {
  195. // When deleting the entity, both the original and the thumbnail will be removed
  196. // when keepFilesOnDelete is set to false
  197. return [
  198. $path . $entity->{$field},
  199. $path . 'thumbnail-' . $entity->{$field},
  200. ];
  201. },
  202. 'keepFilesOnDelete' => false,
  203. ]
  204. ]);
  205. }
  206. }
  207. ?>
  208. .. code:: php
  209. <?php
  210. /*
  211. In the present example, these changes would be made in:
  212. templates/Users/add.php
  213. templates/Users/edit.php
  214. */
  215. ?>
  216. <?= $this->Form->create($user, ['type' => 'file']); ?>
  217. <?= $this->Form->control('username'); ?>
  218. <?= $this->Form->control('photo', ['type' => 'file']); ?>
  219. <?= $this->Form->end(); ?>
  220. Displaying links to files in your view
  221. --------------------------------------
  222. Once your files have been uploaded you can link to them using the ``HtmlHelper``
  223. by specifying the path and using the file information from the database.
  224. This example uses the `default behaviour configuration <configuration.html>`__ using the model ``Example``.
  225. .. code:: php
  226. <?php
  227. /*
  228. In the present example, variations on these changes would be made in:
  229. templates/Users/view.php
  230. templates/Users/index.php
  231. */
  232. // assuming an entity that has the following
  233. // data that was set from your controller to your view
  234. $entity = new Entity([
  235. 'photo' => 'imageFile.jpg',
  236. 'photo_dir' => '7',
  237. ]);
  238. $this->set('entity', $entity);
  239. // You could use the following to create a link to
  240. // the image (with default settings in place of course)
  241. echo $this->Html->link('../files/example/image/' . $entity->photo_dir . '/' . $entity->photo);
  242. ?>
  243. For Windows systems you'll have to build a workaround as Windows systems use backslashes as directory separator which isn't useable in URLs.
  244. .. code:: php
  245. <?php
  246. /*
  247. In the present example, variations on these changes would be made in:
  248. templates/Users/view.php
  249. templates/Users/index.php
  250. */
  251. // assuming an entity that has the following
  252. // data that was set from your controller to your view
  253. $entity = new Entity([
  254. 'photo' => 'imageFile.jpg',
  255. 'photo_dir' => '7',
  256. ]);
  257. $this->set('entity', $entity);
  258. // You could use the following to create a link to
  259. // the image (with default settings in place of course)
  260. echo $this->Html->link('../files/example/image/' . str_replace('\', '/', $entity->photo_dir) . '/' . $entity->photo);
  261. ?>
  262. You can optionally create a custom helper to handle url generation, or contain that within your entity. As it is impossible to detect what the actual url for a file should be, such functionality will *never* be made available via this plugin.