• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP DI\Service类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中Framework\DI\Service的典型用法代码示例。如果您正苦于以下问题:PHP Service类的具体用法?PHP Service怎么用?PHP Service使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Service类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: run

 public function run()
 {
     $request = Service::get('request');
     $router = Service::get('router')->getRoute();
     $controller = $router['controller'];
     $action = $router['action'];
 }
开发者ID:TimSoy,项目名称:test,代码行数:7,代码来源:application.php


示例2: attemptToFindRoute

 public function attemptToFindRoute()
 {
     $request = Service::get('request');
     $uri = $request->getURI();
     if ($uri != '/') {
         rtrim($uri, '/');
     }
     $result = NULL;
     foreach ($this->routes as $route => $rContent) {
         $requirements = isset($rContent["_requirements"]) ? $rContent["_requirements"] : NULL;
         $pattern = preg_replace('~\\{\\w+\\}~', isset($requirements["id"]) ? '(' . $requirements["id"] . ')' : '([\\w\\d]+)', $rContent['pattern']);
         //����� �������� ���� ������� ��������� � requirements � ����������� ������������� (c)����
         if (preg_match(self::DLMTR . "^" . $pattern . "\$" . self::DLMTR, $uri, $match) && isset($requirements["_method"])) {
             if ($requirements["_method"] !== $request->getMethod()) {
                 continue;
             }
             $result = $this->routes[$route];
             $result['name'] = $route;
             if (!empty($match[1])) {
                 $result['variables'] = [$match[1]];
             }
             self::$currentRoute = $result;
             return $result;
         }
         if (preg_match(self::DLMTR . "^" . $pattern . "\$" . self::DLMTR, $uri, $match)) {
             $result = $this->routes[$route];
             $result['name'] = $route;
             if (!empty($match[1])) {
                 $result['variables'] = [$match[1]];
             }
             self::$currentRoute = $result;
             return $result;
         }
     }
 }
开发者ID:smackmybitchup,项目名称:corelabs,代码行数:35,代码来源:Router.php


示例3: render

 /**
  * Render specified template file with data provided
  * @param $template_path Template file path (full)
  * @param array $data Data array
  * @param bool|true $wrap To be wrapped with main template if true
  * @return bool|html
  * @throws FileException if template file does not exist
  */
 public function render($template_path, $data = array(), $wrap = true)
 {
     //Launches the appropriate event
     Service::get('eventManager')->trigger('renderAction', "Render specified template file \"" . $template_path . "\" with data provided");
     $data['include'] = function ($controllerName, $actionName, $params) {
         Helper::dispatch($controllerName, $actionName, $params);
     };
     $data['getRoute'] = function ($route_name, $params = array()) {
         return Service::get('router')->buildRoute($route_name, $params);
     };
     $data['generateToken'] = function () {
         echo '<input type="hidden" name="token" value="' . Service::get('session')->get('token') . '"/>';
     };
     $data['route'] = Registry::getConfig('route');
     $data['user'] = Service::get('session')->get('user');
     if (!$wrap) {
         //Gets messages from session message container to display them in view
         $flush = Service::get('session')->get('messages') ? Service::get('session')->get('messages') : array();
         Service::get('session')->del('messages');
     }
     extract($data);
     //Checks if template file exists
     if (file_exists($template_path)) {
         ob_start();
         include $template_path;
         $content = ob_get_contents();
         ob_end_clean();
     } else {
         throw new FileException("File " . $template_path . " does not found");
     }
     if ($wrap) {
         $content = $this->renderMain($content);
     }
     return $content;
 }
开发者ID:IgorTokman,项目名称:mindk_blog,代码行数:43,代码来源:Renderer.php


示例4: uploadImage

 public function uploadImage($image, $alt)
 {
     try {
         $file = new File($image, 10000);
         $uploadDir = ASSETS . 'uploads/portfolio/gallery/';
         $tmp = ASSETS . 'uploads/portfolio/tmp/';
         $file->setUploadDir($tmp);
         $fileSaver = new FileSaver($file);
         if (!$file->isNormalSize()) {
             throw new \Exception('Very big file size');
         }
         if (!$fileSaver->save()) {
             throw new \Exception('File not selected');
         }
         if (!ImageHelper::isImage($fileSaver->uploadedFile, ['gif', 'png', 'jpg', 'jpeg'])) {
             throw new \Exception('File is not image');
         }
         if (file_exists($uploadDir . $file->getName())) {
             $uniqName = FileHelper::getUniqFileName($uploadDir, FileHelper::getFileExtension($file->getName()));
             $file->setName($uniqName);
         }
         FileHelper::move($fileSaver->uploadedFile, $uploadDir . $file->getName());
         $db = Service::get('db');
         $query = 'INSERT INTO ' . self::getTable() . '(name, alt) VALUES (:name, :alt)';
         $stmt = $db->prepare($query);
         if (!$stmt->execute([':name' => $file->getName(), ':alt' => $alt])) {
             throw new \Exception('File not saved into DB');
         }
         Service::get('session')->setFlushMsg('success', 'File successfully downloaded');
     } catch (\Exception $e) {
         Service::get('session')->setFlushMsg('error', $e->getMessage());
         $response = new ResponseRedirect(Request::getHost() . '/admin');
         $response->send();
     }
 }
开发者ID:smackmybitchup,项目名称:corelabs,代码行数:35,代码来源:AddImage.php


示例5: sendHeaders

 /**
  * 
  */
 public function sendHeaders()
 {
     header(Service::get('request')->get('protocol') . ' ' . $this->code . ' ' . self::$msgs[$this->code]);
     foreach ($this->headers as $key => $value) {
         header(sprintf("%s: %s", $key, $value));
     }
 }
开发者ID:denis-test,项目名称:blog,代码行数:10,代码来源:Response.php


示例6: run

 public function run()
 {
     $route = $this->router->parseRoute();
     try {
         if (!empty($route)) {
             if (empty($route['security']) || in_array(Service::get('security')->getUserRole(), @$route['security'])) {
                 $controllerReflection = new \ReflectionClass($route['controller']);
                 $action = $route['action'] . 'Action';
                 if ($controllerReflection->hasMethod($action)) {
                     $controller = $controllerReflection->newInstance();
                     $actionReflection = $controllerReflection->getMethod($action);
                     $response = $actionReflection->invokeArgs($controller, $route['params']);
                     // sending
                     $response->send();
                 }
             } else {
                 throw new AuthRequredException('Login required');
             }
         } else {
             throw new HttpNotFoundException('Route not found!');
         }
     } catch (HttpNotFoundException $e) {
         // Render 404 or just show msg
         echo $e->getMessage();
     } catch (AuthRequredException $e) {
         echo $e->getMessage();
     } catch (\Exception $e) {
         // Do 500 layout...
         echo $e->getMessage();
     }
 }
开发者ID:IgorShumeikoMindk,项目名称:mindk,代码行数:31,代码来源:Application.php


示例7: render

 /**
  * Rendering method
  *
  * @param   string  Layout file name
  * @param   mixed   Data
  *
  * @return  Response
  */
 public function render($layout, $data = array())
 {
     $fullpath = realpath($this->getViewPath() . $layout . '.php');
     $renderer = new Renderer(Service::get('config')['main_layout']);
     $content = $renderer->render($fullpath, $data);
     return new Response($content);
 }
开发者ID:IgorShumeikoMindk,项目名称:mindk,代码行数:15,代码来源:Controller.php


示例8: render

 /**
  * Include HTML layout file and extract data.
  *
  * @return string
  */
 public function render()
 {
     $user = Service::get('session')->get('authenticated');
     $route = Service::get('router')->find();
     $getRoute = function ($route_name, $params = null) {
         $router = Service::get('router');
         return $router->generateRoute($route_name, $params);
     };
     $include = function ($class_name, $action, $params) {
         $response = Service::get('app')->runControllerAction($class_name, $action, $params);
         if (is_object($response)) {
             $response->send();
         }
     };
     $generateToken = function () {
         $token = Service::get('security')->generateToken();
         echo '<input type="hidden" name="token" value="' . $token . '">';
     };
     $data['getRoute'] = $getRoute;
     $data['generateToken'] = $generateToken;
     $data['include'] = $include;
     $data['user'] = $user;
     $data['route'] = $route;
     ob_start();
     extract($this->_data);
     extract($data);
     include $this->_layout;
     $result = ob_get_clean();
     return $result;
 }
开发者ID:benms,项目名称:MK_Framework,代码行数:35,代码来源:Renderer.php


示例9: run

 public function run()
 {
     $router = Service::get('router');
     $route = $router->parseRoute($_SERVER['REQUEST_URI']);
     try {
         //Checks if route is empty
         if (!empty($route)) {
             //Verifies user role if it needs
             if (array_key_exists('security', $route)) {
                 if (is_null($user = Service::get('session')->get('user')) || !in_array($user->role, $route['security'])) {
                     throw new SecurityException("Access is denied");
                 }
             }
             //Returns Response object
             $response = Helper::dispatch($route['controller'], $route['action'], $route['params']);
         } else {
             throw new HttpNotFoundException("Route does not found", 404);
         }
     } catch (SecurityException $e) {
         Service::get('session')->set('returnUrl', Registry::getConfig('route')['pattern']);
         $response = new ResponseRedirect(Service::get('router')->buildRoute('login'));
     } catch (HttpNotFoundException $e) {
         $response = new Response(Service::get('renderer')->render(Registry::getConfig('error_400'), array('code' => $e->getCode(), 'message' => $e->getMessage())));
     } catch (\Exception $e) {
         $response = new Response(Service::get('renderer')->render(Registry::getConfig('error_500'), array('code' => $e->getCode(), 'message' => $e->getMessage())));
     }
     $response->send();
 }
开发者ID:IgorTokman,项目名称:mindk_blog,代码行数:28,代码来源:Application.php


示例10: __construct

 /**
  * Response constructor.
  * @param string $content контент, который вернется в ответе на запрос
  * @param string $response_code HTTP код ответа, 200 по умолчанию
  * @param string $content_type HTTP тип коннтенат ответа, по умолчанию - text/html
  */
 public function __construct($content, $response_code = ResponseType::OK, $content_type = "text/html")
 {
     $this->content = $content;
     $this->response_code = $response_code;
     $this->content_type = $content_type;
     self::$logger = Service::get("logger");
 }
开发者ID:Artiomtb,项目名称:MindKBlog,代码行数:13,代码来源:Response.php


示例11: __construct

 /**
  * Class instance constructor
  *
  * @param $main_layout
  */
 public function __construct($main_layout)
 {
     $this->main_layout = $main_layout;
     $this->helpers = array('include' => function ($controller, $action, $params) {
         $controllerReflection = new \ReflectionClass($controller);
         $action = $action . 'Action';
         if ($controllerReflection->hasMethod($action)) {
             $controller = $controllerReflection->newInstance();
             $actionReflection = $controllerReflection->getMethod($action);
             $response = $actionReflection->invokeArgs($controller, $params);
             $response->sendBody();
         }
     }, 'generateToken' => function () {
         $token = Service::get('security')->getToken();
         echo '<input type="hidden" name="token" value="' . $token . '" />';
     }, 'getRoute' => function ($route, $params = array()) {
         return Service::get('router')->getRoute($route, $params);
     });
     if (Service::get('security')->isAuthenticated()) {
         $this->data['user'] = Service::get('session')->user;
     } else {
         $this->data['user'] = null;
     }
     $this->data['flush'] = Service::get('session')->getFlush();
 }
开发者ID:denis-test,项目名称:blog,代码行数:30,代码来源:Renderer.php


示例12: solveException

 /**
  * @throws ServiceException
  *
  * solve exception depending from enter message (number or string)
  * if message is numeric get code from Response class and redirect to 500 html page
  * if string redirect to $redirectAddress
  */
 public function solveException()
 {
     $data = array();
     if ($this->getMessage() && is_numeric($this->getMessage())) {
         $data['code'] = $this->getMessage();
         $data['message'] = Response::getMessageByCode($this->getMessage());
         if ($this->beforeSolve) {
             $this->beforeSolveException();
         }
         $renderer = new Renderer();
         $responce = new Response($renderer::render(Service::get('config')->get500Layout(), $data), 'text/html', 202);
         $responce->send();
     } else {
         if ($this->getMessage()) {
             Service::get('session')->addFlush($this->type, $this->getMessage());
             if ($this->beforeSolve) {
                 $this->beforeSolveException();
             }
             echo $this->redirectAddress;
             $redirect = new ResponseRedirect($this->redirectAddress);
             $redirect->sendHeaders();
         } else {
             throw new ServiceException(500);
         }
     }
 }
开发者ID:VinokurYurii,项目名称:Homework,代码行数:33,代码来源:MainException.php


示例13: execute

 /**
  * Divide uri and call the appropriate controllers, methods and params.
  *
  * @param string $uri Uri.
  *
  * @return array An array which contains the required controllers, methods and params.
  * @throws \Framework\Exception\DIException
  */
 public function execute($uri = null)
 {
     if ($uri === null) {
         $uri = Service::get('request')->getUri();
     }
     $uri = '/' . trim(trim($uri), '/');
     foreach ($this->routes as $name => $route) {
         $pattern = str_replace(array('{', '}'), array('(?P<', '>)'), $route['pattern']);
         if (array_key_exists('_requirements', $route)) {
             if (array_key_exists('_method', $route['_requirements']) && $route['_requirements']['_method'] != Service::get('request')->getMethod()) {
                 continue;
             }
             if (0 !== count($route['_requirements'])) {
                 $search = $replace = array();
                 foreach ($route['_requirements'] as $key => $value) {
                     $search[] = '<' . $key . '>';
                     $replace[] = '<' . $key . '>' . $value;
                 }
                 $pattern = str_replace($search, $replace, $pattern);
             }
         }
         if (!preg_match('&^' . $pattern . '$&', $uri, $params)) {
             continue;
         }
         $params = array_merge(array('controller' => $route['controller'], 'action' => $route['action']), $params);
         foreach ($params as $key => $value) {
             if (is_int($key)) {
                 unset($params[$key]);
             }
         }
         $this->currentRoute = array_merge($route, array('_name' => $name));
         return $params;
     }
 }
开发者ID:cheebam,项目名称:blog,代码行数:42,代码来源:Router.php


示例14: updateAction

 public function updateAction()
 {
     $errors = array();
     $msgs = array();
     $user_id = Service::get('Session')->user->id;
     if (isset(Service::get('Session')->profile)) {
         $profile = Service::get('Session')->profile;
     } else {
         $profile = Profile::getProfile($user_id);
     }
     if (!$profile) {
         $profile = new Profile();
         $profile->user_id = $user_id;
     }
     if ($this->getRequest()->isPost()) {
         try {
             $profile->name = $this->getRequest()->post('name');
             $profile->second_name = $this->getRequest()->post('second_name');
             $profile->info = $this->getRequest()->post('info');
             $validator = new Validator($profile);
             if ($validator->isValid()) {
                 $profile->save();
                 return $this->redirect($this->generateRoute('home'), 'The data has been saved successfully');
             } else {
                 $errors = $validator->getErrors();
             }
         } catch (DatabaseException $e) {
             $msgs = $e->getMessage();
         }
     }
     return $this->render('profile.html', array('errors' => $errors, 'msgs' => $msgs, 'profile' => $profile));
 }
开发者ID:denis-test,项目名称:blog,代码行数:32,代码来源:ProfileController.php


示例15: render

 /**
  * Create page
  *
  * @param $path_to_layout
  * @param $content
  * @return string
  */
 public function render($path_to_layout, $content)
 {
     $include = function ($controller, $action, $params = array()) {
         $app = Service::get('app');
         $app->generateResponseCtrl($controller, $action, $params);
     };
     $user = Service::get('session')->get('user');
     //массив
     $router = Service::get('route');
     $getRoute = function ($rout) use(&$router) {
         return $router->buildRoute($rout);
     };
     $generateToken = function () {
         $csrf = Service::get('csrf');
         $token = $csrf->generateToken();
         echo '<input type="hidden" name="token" value="' . $token . '" />';
     };
     ob_start();
     if (is_array($content)) {
         extract($content);
     }
     include $path_to_layout;
     //костыль на отобжажение ссылки на редактирование поста, чтобы не менять стандартную вьюху show.html
     if (!empty($content['post']->id) && Service::get('security')->isAuthenticated() && empty($content['show'])) {
         echo '<br/><a href="/posts/' . $content['post']->id . '/edit"> Edit post</a>';
         echo '<br/><a href="/posts/' . $content['post']->id . '/delete"> Delete post</a>';
     }
     return ob_get_clean();
 }
开发者ID:Alexandr93,项目名称:blog,代码行数:36,代码来源:Renderer.php


示例16: signinAction

 public function signinAction()
 {
     if (Service::get('security')->isAuthenticated()) {
         return new ResponseRedirect($this->generateRoute('home'));
     }
     $errors = array();
     if ($this->getRequest()->isPost()) {
         try {
             if ($user_mas = User::findByEmail($this->getRequest()->post('email'))) {
                 array_push($errors, 'This email is already register!');
                 return $this->render('signin.html', array('errors' => $errors));
             } else {
                 $user = new User();
                 $user->email = $this->getRequest()->post('email');
                 $user->password = $this->getRequest()->post('password');
                 $user->role = 'ROLE_USER';
                 $user->save();
                 $user_mas = User::findByEmail($this->getRequest()->post('email'));
                 Service::get('security')->setUser($user_mas);
                 return $this->redirect($this->generateRoute('home'));
             }
         } catch (DatabaseException $e) {
             $errors = array($e->getMessage());
         }
     }
     return $this->render('signin.html', array('errors' => $errors));
 }
开发者ID:Roman2016,项目名称:mindk_framework,代码行数:27,代码来源:SecurityController.php


示例17: run

 /**
  * 
  * @throws HttpNotFoundException
  * @throws BadResponseTypeException
  */
 public function run()
 {
     $route = Service::get('router')->parseRoute(Service::get('request')->get('uri'));
     try {
         if (empty($route)) {
             throw new HttpNotFoundException('Route not found', 404);
         }
         $controllerReflection = new \ReflectionClass($route['controller']);
         $action = $route['action'] . 'Action';
         if ($controllerReflection->hasMethod($action)) {
             $controller = $controllerReflection->newInstance();
             $actionReflection = $controllerReflection->getMethod($action);
             $this->response = $actionReflection->invokeArgs($controller, $route['params']);
             if ($this->response instanceof Response) {
                 $this->response->send();
             } else {
                 throw new BadResponseTypeException('Result is not instance of Response');
             }
         } else {
             throw new HttpNotFoundException('The method or controller not found', 404);
         }
     } catch (BadResponseTypeException $e) {
         $e->getResponse()->send();
     } catch (HttpNotFoundException $e) {
         $e->getResponse()->send();
     } catch (DatabaseException $e) {
         echo $e->getMessage();
     } catch (AuthRequredException $e) {
         $e->getResponse()->send();
     } catch (\Exception $e) {
         echo $e->getMessage();
     }
 }
开发者ID:denis-test,项目名称:blog,代码行数:38,代码来源:Application.php


示例18: render

 /**
  * Render specified template file with data provided
  *
  * @param   string  Template file path (full)
  * @param   mixed   Data array
  * @param   bool    To be wrapped with main template if true
  *
  * @return  text/html
  */
 public function render($template_path, $data = array(), $wrap = true)
 {
     extract($data);
     ob_start();
     $include = function ($controller, $action, $data = array()) {
         $controller = new $controller();
         $method = $action . 'Action';
         extract($data);
         return $result = $controller->{$method}($id);
     };
     $generateToken = function () {
     };
     $getRoute = function ($key) {
         $controller = Service::get('route_controller')['controller'];
         $controller = new $controller();
         return $controller->generateRoute($key);
     };
     include $template_path;
     $content = ob_get_contents();
     ob_end_clean();
     if ($wrap) {
         $content = $this->renderMain($content);
     }
     return $content;
 }
开发者ID:IgorShumeikoMindk,项目名称:mindk,代码行数:34,代码来源:Renderer.php


示例19: render

 /**
  * Renders
  *
  * @param $templatePath
  * @param $data
  * @param bool|true $wrap
  * @return string
  */
 public function render($templatePath, $data, $wrap = true)
 {
     $templatePath = realpath($templatePath);
     $include = function ($controller, $action, $args = array()) {
         $controllerInstance = new $controller();
         if ($args === null) {
             $args = array();
         }
         return call_user_func_array(array($controllerInstance, $action . 'Action'), $args);
     };
     $generateToken = function () {
         $token = md5('solt_string' . uniqid());
         setcookie('token', $token);
         echo '<input type="hidden" value="' . $token . '" name="token">';
     };
     $getRoute = function ($name) {
         if (array_key_exists($name, Service::get('routes'))) {
             $uri = Service::get('routes')[$name]['pattern'];
             return $uri;
         }
     };
     extract($data);
     ob_start();
     if (file_exists($templatePath)) {
         include $templatePath;
     }
     $content = ob_get_contents();
     ob_end_clean();
     if ($wrap) {
         $content = $this->renderMain($content);
     }
     return $content;
 }
开发者ID:ShepelevD,项目名称:Framework-PHP,代码行数:41,代码来源:Renderer.php


示例20: loadErrorHandler

 /**
  * Registers custom error handler
  *
  * @access public
  * @static
  *
  * @return void
  */
 public static function loadErrorHandler()
 {
     set_error_handler(function ($errno, $errmsg, $filename, $linenum) {
         $date = date('Y-m-d H:i:s (T)');
         if (!file_exists(__DIR__ . '/../../app/logs/')) {
             mkdir(__DIR__ . '/../../app/logs/');
         }
         $f = fopen(__DIR__ . '/../../app/logs/errorlog.txt', 'a');
         if (!empty($f)) {
             $error = "____________________________________________________________\n";
             $error .= $date . "\n";
             $error .= $errno . "\n";
             $error .= $errmsg . "\n";
             $error .= $filename . "\n";
             $error .= $linenum . "\n";
             $error .= "____________________________________________________________\n";
             fwrite($f, $error);
             fclose($f);
         }
         if (Service::get('config')['mode'] == 'user') {
             $renderer = new Renderer(Service::get('config')['layouts']);
             $renderer->set('code', 500);
             $renderer->set('message', 'Oooops');
             $content = $renderer->generatePage('500.html');
             $response = new Response($content, array(), 500);
             $response->send();
         }
     });
 }
开发者ID:GerashenkoVladimir,项目名称:myblog,代码行数:37,代码来源:ErrorHandler.php



注:本文中的Framework\DI\Service类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP assets\AppAsset类代码示例发布时间:2022-05-23
下一篇:
PHP Framework\Registry类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap