📜 ⬆️ ⬇️

Controller for working with media files in Kohana

Greetings
This article will be more useful for newbies, but, given the lack of extensive documentation on the framework, there are a lot of them and so I decided to publish it.
Writing this article also led me to a lot of questions related to working with media files in Kohana and some pieces of code in many source code projects on Ko3 that I reviewed (I like to consider the implementation of various projects on this framework - sometimes it helps me a lot).
And so, what are we going to do?
We will write a controller that will process requests of the form media / css / default and return to us (cached, if any) the file views /.../ media / css / default.css, for example.

The code is 90% borrowed from the userguide module.

And so, the code:
class Controller_Media extends Kohana_Controller{ public function action_index($path, $file) { $this->request->check_cache(sha1($this->request->uri)); //  media/css  media/js        .css  .js ,   =   if($path == 'css' || $path == 'js') { $ext = $path; } else { $ext = pathinfo($file, PATHINFO_EXTENSION); $file = substr($file, 0, -(strlen($ext) + 1)); } //   View::GetTplName()    ,   -  default, ,   views/default/media/...      -    View::GetTplName()     . if ($file = Kohana::find_file('views/'.View::GetTplName().'/media/'.$path, $file, $ext)) { //      ,    $this->request->response = file_get_contents($file); //        $this->request->headers['Content-Type'] = File::mime_by_ext($ext); $this->request->headers['Content-Length'] = filesize($file); $this->request->headers['Last-Modified'] = date('r', filemtime($file)); } else { //   404,     $this->request->status = 404; } } } 


That's all. Now, to load views / default / media / css / default.css, just go to media / css / default, and to load a picture from, say, views / default / media / img / logo.png, we turn to media / img / logo .png
And for this we will be responsible for such a route:
 Route::set('media', 'media/<path>/<file>', array('file' => '.*')) ->defaults(array( 'controller' => 'media', 'action' => 'index' )); 

')
I am waiting for your comments and I hope that this small post will help someone.

Source: https://habr.com/ru/post/104862/


All Articles