本文整理汇总了PHP中Framework\DI\Service::get方法的典型用法代码示例。如果您正苦于以下问题:PHP Service::get方法的具体用法?PHP Service::get怎么用?PHP Service::get使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Framework\DI\Service
的用法示例。
在下文中一共展示了Service::get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: 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));
}
示例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: 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;
}
示例7: getContentBuffer
public function getContentBuffer()
{
$title = Service::getConfig('title');
extract($this->data);
$route = Router::$currentRoute;
$getRoute = $this->getRouteClosure();
$user = Service::get('security')->getUser();
$include = $this->getIncludeClosure();
$flush = Service::get('session')->getFlushMsgs();
$generateToken = $this->getGenerateTokenClosure();
//@TODO: describe below!
if (file_exists($this->viewPath)) {
ob_start();
include $this->viewPath;
$content = ob_get_clean();
if (isset($layout) && $layout == false) {
return $content;
}
} else {
//@TODO::WARNINGS be
$message = "Server error";
$code = 500;
ob_start();
include $this->error_500;
$content = ob_get_clean();
if (isset($layout) && $layout == false) {
return $content;
}
}
ob_start();
include $this->_layout;
$buffer = ob_get_clean();
return $buffer;
}
示例8: 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();
}
示例9: 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));
}
示例10: __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();
}
示例11: 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;
}
示例12: __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");
}
示例13: 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);
}
}
}
示例14: 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;
}
}
示例15: 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();
}
}