本文整理汇总了PHP中Framework\DI\Service类的典型用法代码示例。如果您正苦于以下问题:PHP Service类的具体用法?PHP Service怎么用?PHP Service使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Service类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: run
public function run()
{
$request = Service::get('request');
$router = Service::get('router')->getRoute();
$controller = $router['controller'];
$action = $router['action'];
}
示例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;
}
}
}
示例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;
}
示例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();
}
}
示例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));
}
}
示例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();
}
}
示例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);
}
示例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;
}
示例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();
}
示例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");
}
示例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();
}
示例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);
}
}
}
示例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;
}
}
示例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));
}
示例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();
}