use Symfony\Component\Translation\Loader\YamlFileLoader; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; require_once 'bootstrap.php'; require_once 'config.php'; $app = new Silex\Application(); // turn on debug mode $app['debug'] = DEBUG_MODE; // enable translations $app['locale'] = 'en_GB'; $app->before(function () use($app) { if ($locale = $app['request']->get('locale')) { $app['locale'] = $locale; $app['session']->set('locale', $locale); } else { if ($locale = $app['session']->get('locale')) { $app['locale'] = $locale; } } }); // do some security stuff $app->after(function (Request $request, Response $response) { $response->headers->set('X-Frame-Options', 'DENY'); $response->headers->set('X-Content-Type-Options', 'nosniff'); $response->headers->set('X-UA-Compatible', 'IE=edge'); }); $app->register(new Silex\Provider\TranslationServiceProvider(), array('locale_fallbacks' => array('en_GB'))); $app['translator'] = $app->share($app->extend('translator', function ($translator, $app) { $translator->addLoader('yaml', new YamlFileLoader()); $translator->addResource('yaml', __DIR__ . '/../translations/en_GB.yml', 'en_GB'); //$translator->addResource('yaml', __DIR__.'/../translations/fi_FI.yml', 'fi_FI');
}); include __DIR__ . '/config/container.php'; $app->before(function (Request $request) use($app) { $whiteLists = (include __DIR__ . '/whiteList.php'); $whiteLists = $request->getMethod() == 'GET' ? $whiteLists['get'] : $whiteLists['post']; $inWhiteList = 0; foreach ($whiteLists as $whiteList) { $path = $request->getPathInfo(); if (preg_match($whiteList, $request->getPathInfo())) { $inWhiteList = 1; break; } } $token = $request->headers->get('Auth-Token', ''); if (!$inWhiteList && empty($token)) { throw createNotFoundException("AuthToken is not exist."); } $userService = ServiceKernel::instance()->createService('User.UserService'); $token = $userService->getToken('mobile_login', $token); if (!$inWhiteList && empty($token['userId'])) { throw createAccessDeniedException("AuthToken is invalid."); } $user = $userService->getUser($token['userId']); // $user = $userService->getUser(1); if (!$inWhiteList && empty($user)) { throw createNotFoundException("Auth user is not found."); } setCurrentUser($user); }); $app->error(function (\Exception $e, $code) { return array('code' => $code, 'message' => $e->getMessage());
<?php //ini_set("display_errors", true); use Silex\Provider\ServiceControllerServiceProvider; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\JsonResponse; require_once __DIR__ . "/../vendor/autoload.php"; $app = new Silex\Application(); require_once __DIR__ . "/../resources/config.php"; // Accept and decode JSON data before the call to controllers $app->before(function (Request $request) { if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) { $data = json_decode($request->getContent(), true); $request->request->replace(is_array($data) ? $data : array()); } }); // Add correct headers before it is sent to the client $app->after(function (Request $request, Response $response) { $response->headers->set("Access-Control-Allow-Origin", "*"); $response->headers->set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); }); $app->register(new ServiceControllerServiceProvider()); $connection = new RestApp\Service\PDOConnection($app); $app['todo.repo'] = $app->share(function () use($connection) { return new RestApp\Repository\TodoRepository($connection); }); $app['todo.controller'] = $app->share(function () use($app) { return new RestApp\Controller\TodoController($app['todo.repo']); }); $app['converter.user'] = $app->share(function () use($app) {
$app['serializer'] = $app->share(function () use($app) { $jmsSerializerBuilder = JMS\Serializer\SerializerBuilder::create()->setMetadataDirs(array('' => __DIR__ . '/config/serializer', 'Propilex' => __DIR__ . '/config/serializer'))->setDebug($app['debug'])->setCacheDir(__DIR__ . '/cache/serializer'); return Hateoas\HateoasBuilder::create($jmsSerializerBuilder)->setMetadataDirs(array('' => __DIR__ . '/config/serializer', 'Propilex' => __DIR__ . '/config/serializer'))->setDebug($app['debug'])->setCacheDir(__DIR__ . '/cache/hateoas')->setUrlGenerator(null, new SymfonyUrlGenerator($app['url_generator']))->setUrlGenerator('templated', new SymfonyUrlGenerator($app['templated_uri_generator']))->setXmlSerializer(new XmlHalSerializer())->addConfigurationExtension(new CuriesConfigurationExtension($app['curies_route_name'], 'templated'))->setExpressionContextVariable('curies_prefix', $app['curies_prefix'])->registerExpressionFunction(new TransExpressionFunction($app['translator']))->build(); }); $app['hateoas.pagerfanta_factory'] = $app->share(function () use($app) { return new PagerfantaFactory(); }); // Translation $app->register(new Silex\Provider\TranslationServiceProvider()); $app->before(function (Request $request) use($app) { $validatorFile = __DIR__ . '/../vendor/symfony/validator/Symfony/Component/Validator/Resources/translations/validators.%s.xlf'; $locale = $request->attributes->get('_language', 'en'); $app['translator']->setLocale($locale); $app['translator']->addLoader('xlf', new Symfony\Component\Translation\Loader\XliffFileLoader()); $app['translator']->addResource('xlf', sprintf($validatorFile, $locale), $locale, 'validators'); $messagesLocale = $locale; if (!is_file($messagesFile = __DIR__ . '/config/messages.' . $messagesLocale . '.yml')) { $messagesFile = sprintf(__DIR__ . '/config/messages.%s.yml', $app['translation.fallback']); $messagesLocale = $app['translation.fallback']; } $app['translator']->addLoader('yml', new Symfony\Component\Translation\Loader\YamlFileLoader()); $app['translator']->addResource('yml', $messagesFile, $messagesLocale); }); $app['templated_uri_generator'] = $app->share(function () use($app) { return new Rfc6570Generator($app['routes'], $app['request_context']); }); // Markdown $app->register(new Nicl\Silex\MarkdownServiceProvider()); // Negotiation $app->register(new KPhoen\Provider\NegotiationServiceProvider(['json' => ['application/hal+json', 'application/json'], 'xml' => ['application/hal+xml', 'application/xml']])); // Document validator $app['document_validator'] = $app->protect(function (Document $document) use($app) {
require_once __DIR__ . '/backend/DBController.php'; require_once __DIR__ . '/backend/Schema.php'; /* |-------------------------------------------------------------------------- | Create new application instance. |-------------------------------------------------------------------------- */ $app = new Silex\Application(); $app['base_dir'] = __DIR__; $app['debug'] = true; date_default_timezone_set('Europe/Vilnius'); $app->before(function (Symfony\Component\HttpFoundation\Request $request, $app) { if (!isset($app['base_url'])) { $app['base_url'] = rtrim($request->getSchemeAndHttpHost() . $request->getBaseUrl(), '/'); } if (strpos($request->headers->get('Content-Type'), 'application/json') === 0) { $data = json_decode($request->getContent(), true); $request->request->replace(is_array($data) ? $data : array()); } }); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__)); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Shop\Database\DatabaseServiceProvider()); $app['illuminate.capsule']->bootEloquent(); $app['illuminate.capsule']->setAsGlobal(); $app['db.controller'] = $app->share(function () use($app) { return new Shop\Database\DBController($app, new \Shop\Database\Schema()); }); $app['db.controller']->createDB(); $app['home.controller'] = $app->share(function () use($app) { return new Shop\Home\HomeController($app);
$app['debug'] = true; // Config // ------ $env = getenv('APP_ENV') ?: 'prod'; $app->register(new Igorw\Silex\ConfigServiceProvider(__DIR__ . '/../config/' . $env . '.yml')); // Twig // ---- $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views')); $app['twig'] = $app->share($app->extend('twig', function ($twig, $app) { $twig->addFunction(new \Twig_SimpleFunction('asset', function ($asset) use($app) { return sprintf('%s/%s', trim($app['request']->getBasePath()), ltrim($asset, '/')); })); return $twig; })); $app->before(function ($request) use($app) { $app['twig']->addGlobal('active', $request->get('_route')); }); // Swift Mailer // ------------ $app->register(new Silex\Provider\SwiftmailerServiceProvider()); $app['swiftmailer.options'] = array('host' => 'localhost', 'port' => 25, 'username' => '', 'password' => '', 'encryption' => null, 'auth_mode' => null); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); // CORS Cross-Origin Resource Sharing // ---------------------------------- $http_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : NULL; if (in_array($http_origin, $app['cors_allowed_origins'])) { $app->register(new JDesrosiers\Silex\Provider\CorsServiceProvider(), array('cors.allowOrigin' => $http_origin)); $app->after($app['cors']); } // Logging // -------
$app->register(new FormExtension()); $app->register(new TranslationExtension(), array('translator.messages' => array())); $app->register(new TwigExtension(), array('twig.path' => array(__DIR__ . '/templates', __DIR__ . '/../vendor/Symfony/Bridge/Twig/Resources/views/Form'), 'twig.class_path' => __DIR__ . '/../vendor/silex/vendor/twig/lib')); $app->register(new DoctrineMongoDBExtension(), array('doctrine.odm.mongodb.connection_options' => array('database' => 'springbok-silex', 'host' => 'localhost'), 'doctrine.odm.mongodb.documents' => array(array('type' => 'annotation', 'path' => __DIR__ . '/Document', 'namespace' => 'Document')), 'doctrine.odm.mongodb.metadata_cache' => 'array', 'doctrine.common.class_path' => __DIR__ . '/../vendor/mongodb-odm/lib/vendor/doctrine-common/lib', 'doctrine.mongodb.class_path' => __DIR__ . '/../vendor/mongodb-odm/lib/vendor/doctrine-mongodb/lib', 'doctrine.odm.mongodb.class_path' => __DIR__ . '/../vendor/mongodb-odm/lib')); $app['doctrine.odm.mongodb.hydrators_dir'] = __DIR__ . '/../cache/doctrine/hydrators'; Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver::registerAnnotationClasses(); require_once __DIR__ . '/config.php'; if (!is_dir($app['doctrine.odm.mongodb.hydrators_dir'])) { mkdir($app['doctrine.odm.mongodb.hydrators_dir'], 0777, true); } $app->before(function () use($app) { if (!isset($app['culin.entity'])) { throw new \RuntimeException('Configuration entry "culin.entity" is not set'); } $app['repository'] = $app['doctrine.odm.mongodb.dm']->getRepository($app['culin.entity']); $app['query_builder'] = $app->share(function ($app) { return $app['doctrine.odm.mongodb.dm']->createQueryBuilder($app['culin.entity']); }); $app['form'] = $app->share(function ($app) { return function ($entity = null) use($app) { return $app['form.factory']->create(new $app['culin.form'](), $entity); }; }); $app['twig']->addExtension(new CulinExtension($app)); $app['twig']->addExtension(new \Twig_Extensions_Extension_Debug()); $app['twig']->enableDebug(); }); $app->after(function () use($app) { $app['doctrine.odm.mongodb.dm']->flush(); }); return $app;
return ""; }); $app->error(function (\Exception $e, $code) { global $me, $tmpl, $view; switch ($code) { case 403: $me->params["err"] = "e403"; $me->view = __DIR__ . '/views/v.err.php'; $me->tmpl = __DIR__ . '/templates/t.err.php'; break; case 404: $me->params["err"] = "e404"; $me->view = __DIR__ . '/views/v.err.php'; $me->tmpl = __DIR__ . '/templates/t.err.php'; break; default: $me->params["err"] = "hz"; $me->view = __DIR__ . '/views/v.err.php'; $me->tmpl = __DIR__ . '/templates/t.err.php'; } return ""; }); $app->before(function () { global $me, $tmpl, $view; }); $app->finish(function () { global $me, $tmpl, $view; }); $app->run(); require_once $me->view; require_once __DIR__ . '/templates/t.common.php';
$app->register(new UrlGeneratorServiceProvider()); $app->register(new SessionServiceProvider()); $app->register(new Silex\Provider\TranslationServiceProvider(), array('locale_fallback' => $config['locale'], 'locale' => $config['locale'], 'translator.domains' => array())); // enable database $app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'pdo_sqlite', 'path' => MAIN_PATH . '/app.db'))); // enable localization $app['translator'] = $app->share($app->extend('translator', function (Silex\Translator $translator) { $translator->addLoader('yaml', new YamlFileLoader()); $translator->addResource('yaml', MAIN_PATH . '/locales/en.yml', 'en'); $translator->addResource('yaml', MAIN_PATH . '/locales/ru.yml', 'ru'); return $translator; })); $app->register(new Silex\Provider\MonologServiceProvider(), array('monolog.logfile' => MAIN_PATH . '/logs/app.log')); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => array(MAIN_PATH . '/views'), 'twig.options' => array('cache' => MAIN_PATH . '/cache/twig'))); $app->before(function () use($app) { $app['translator']->addLoader('xlf', new XliffFileLoader()); $app['translator']->addResource('xlf', __DIR__ . '/../vendor/symfony/validator/Resources/translations/validators.ru.xlf', 'ru', 'validators'); }); /** @var \Symfony\Component\HttpFoundation\Session\Session $session */ $session = $app['session']; $session->start(); if ($lang = $session->get('locale', $config['locale'])) { // apply localization /*$app->before(function () use ($app, $lang) { $app['locale'] = $lang; return $app; });*/ $app['locale'] = $lang; $app['locale_fallback'] = $lang; } require_once MAIN_PATH . '/controllers/error.php';
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views')); // Register Doctrine (mySql provider) $configuration = getConfiguration(); $app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'pdo_mysql', 'host' => $configuration['host'], 'dbname' => $configuration['dbname'], 'user' => $configuration['user'], 'password' => $configuration['password'], 'charset' => 'utf8', 'driverOptions' => array(1002 => 'SET NAMES utf8')))); // Register Security Provider $app->register(new Silex\Provider\SecurityServiceProvider(), array('security.firewalls' => array('account' => array('pattern' => '^/account/', 'form' => array('login_path' => '/login', 'check_path' => '/account/login_check'), 'logout' => array('logout_path' => '/account/logout'), 'users' => $app->share(function () use($app) { return new UserProvider($app['db']); }))))); // Managers declaration $app['accountManager'] = function ($app) { return new AccountManager($app['db'], $app["monolog"]); }; // Before all actions $app->before(function (Request $request) use($app) { $language = getHeaderLanguage($request); $app["monolog"]->addInfo("Locate to: " . $language); $app["translator"]->setLocale($language); }); // Managing exceptions $app->error(function (\Exception $e, $code) { return new Response('Se ha producido un error.\\n' . print_r($e, true) . "\nCode: " . $code); }); $app->get('/', function () use($app) { $app["monolog"]->addInfo("Root page"); return $app["twig"]->render("home.twig"); }); $app->post('/', function (Request $request) use($app) { $email = $request->get('email'); $app["monolog"]->addInfo("Save Mail: {$email}"); // Validates and Saves $isValid = filter_var($email, FILTER_VALIDATE_EMAIL) && $app['accountManager']->saveMail($email);
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; require_once __DIR__ . '/vendor/autoload.php'; require_once __DIR__ . '/config.php'; $app = new Silex\Application(); /*** * * Accepting JSON in request body. * @note: the method described in http://silex.sensiolabs.org/doc/cookbook/json_request_body.html doesn't allow us to get the whole parameter array. * */ $app->before(function (Request $request) use($app) { if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) { $app['data'] = json_decode($request->getContent(), true); } }); /*** * * Endpoints. * @see https://github.com/okfn/annotator/wiki/Storage * */ $app->get('/', function () use($app) { $out = array('name' => "Annotator Store API (PHP)", 'version' => '1.0.0', 'author' => 'julien-c'); return $app->json($out); }); $app->get('/annotations', function () use($app) { $out = array(); $m = new Mongo();
$app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->view(function (array $result, Request $request) use($app) { // 兼容气球云搜索的接口 $documentType = $request->headers->get('X-Search-Document'); if ($documentType) { $class = "Topxia\\Api\\SpecialResponse\\{$documentType}Response"; if (!class_exists($class)) { throw new \RuntimeException("{$documentType}Response不存在!"); } $obj = new $class(); $result = $obj->filter($result); } return new JsonResponse($result); }); $app->before(function (Request $request) use($app) { $auth = new ApiAuth(include __DIR__ . '/config/whitelist.php'); $auth->auth($request); }); $app->error(function (\Exception $exception, $code) use($app) { $error = array('code' => $code, 'message' => $exception->getMessage()); if ($app['debug']) { if (!$exception instanceof FlattenException) { $exception = FlattenException::create($exception); } $error['previous'] = array(); $flags = PHP_VERSION_ID >= 50400 ? ENT_QUOTES | ENT_SUBSTITUTE : ENT_QUOTES; $count = count($exception->getAllPrevious()); $total = $count + 1; foreach ($exception->toArray() as $position => $e) { $previous = array(); $ind = $count - $position + 1; $previous['message'] = "{$ind}/{$total} {$e['class']}: {$e['message']}";
}; // // Twig $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../app/views')); // // Session $app->register(new Silex\Provider\SessionServiceProvider()); // // translations $app->before(function () use($app) { $app->register(new Silex\Provider\TranslationServiceProvider(), array('locale_fallback' => 'en', 'translation.class_path' => __DIR__ . '/../lib/vendor/symfony/src')); $app['translator']->addLoader('yml', new Symfony\Component\Translation\Loader\YamlFileLoader()); $app['translator']->addResource('yml', __DIR__ . '/../app/translations/en.yml', 'en'); $app['translator']->addResource('yml', __DIR__ . '/../app/translations/fr.yml', 'fr'); $app['translator.loader'] = new Symfony\Component\Translation\Loader\YamlFileLoader(); $app['twig']->addExtension(new Symfony\Bridge\Twig\Extension\TranslationExtension($app['translator'])); $app->before(function () use($app) { if ($locale = $app['request']->get('locale')) { $app['locale'] = $locale; } }); }); // // Application // -------------------------------------------------------- // // listing $app->get('/', function () use($app) { $repository = $app['hbt.feature.repository']; return $app['twig']->render('feature/list.html.twig', array('features' => $repository->getFeatures(), 'pendingFeatures' => $repository->getPendingFeatures(), 'failingFeatures' => $repository->getFailingFeatures(), 'validFeatures' => $repository->getValidFeatures())); });
require __DIR__ . '/config.php'; $app->register(new HttpCacheServiceProvider()); $app->register(new SessionServiceProvider()); $app->register(new ValidatorServiceProvider()); $app->register(new FormServiceProvider()); $app->register(new UrlGeneratorServiceProvider()); $app->register(new TranslationServiceProvider(), array('locale' => $app['locale'])); $app['translator'] = $app->share($app->extend('translator', function ($translator, $app) { $translator->addLoader('yaml', new YamlFileLoader()); $translator->addResource('yaml', __DIR__ . '/../resources/locales/fr.yml', 'fr'); return $translator; })); // Temporarly hack $app['translator.domains'] = array(); $app->register(new MonologServiceProvider(), array('monolog.logfile' => __DIR__ . '/../log/app.log', 'monolog.name' => 'app', 'monolog.level' => 300)); $app->register(new TwigServiceProvider(), array('twig.options' => array('cache' => false, 'strict_variables' => true), 'twig.form.templates' => array('form_div_layout.html.twig', 'common/form_div_layout.html.twig'), 'twig.path' => array(__DIR__ . '/../views'))); $app->register(new DoctrineServiceProvider(), array('db.options' => array('driver' => $app['db.config.driver'], 'dbname' => $app['db.config.dbname'], 'host' => $app['db.config.host'], 'user' => $app['db.config.user'], 'password' => $app['db.config.password']))); $app->register(new AsseticExtension(), array('assetic.options' => array('debug' => $app['debug']), 'assetic.filters' => $app->protect(function ($fm) use($app) { $fm->set('yui_css', new Assetic\Filter\Yui\CssCompressorFilter($app['assetic.filter.yui_compressor.path'])); $fm->set('yui_js', new Assetic\Filter\Yui\JsCompressorFilter($app['assetic.filter.yui_compressor.path'])); }), 'assetic.assets' => $app->protect(function ($am, $fm) use($app) { $am->set('styles', new Assetic\Asset\AssetCache(new Assetic\Asset\GlobAsset($app['assetic.input.path_to_css'], array()), new Assetic\Cache\FilesystemCache($app['assetic.path_to_cache']))); $am->get('styles')->setTargetPath($app['assetic.output.path_to_css']); $am->set('scripts', new Assetic\Asset\AssetCache(new Assetic\Asset\GlobAsset($app['assetic.input.path_to_js'], array()), new Assetic\Cache\FilesystemCache($app['assetic.path_to_cache']))); $am->get('scripts')->setTargetPath($app['assetic.output.path_to_js']); }))); // Temporary hack. Silex should start session on demand. $app->before(function () use($app) { $app['session']->start(); }); return $app;
$app['debug'] = true; // Services $app->register(new Silex\Provider\FormServiceProvider()); $app->register(new Silex\Provider\TranslationServiceProvider()); $app->register(new Silex\Provider\ValidatorServiceProvider()); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Silex\Provider\SwiftmailerServiceProvider(), array('swiftmailer.options' => array('host' => 'smtp.gmail.com', 'port' => 465, 'username' => '*****@*****.**', 'password' => 'heticp2018smtp', 'encryption' => 'ssl', 'auth_mode' => 'login'))); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views')); $app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'pdo_mysql', 'host' => 'localhost', 'dbname' => 'hetic_p2019_silex_pokedex', 'user' => 'root', 'password' => 'root', 'charset' => 'utf8'))); $app['db']->setFetchMode(PDO::FETCH_OBJ); // Models $pokemons_model = new PokemonsModel($app['db']); $types_model = new TypesModel($app['db']); // Middlewares $app->before(function () use($app) { $app['twig']->addGlobal('title', 'Hetic Pokedex'); }); // Routes $app->get('/', function () use($app) { $data = array(); return $app['twig']->render('pages/home.twig', $data); })->bind('home'); $app->match('/about', function (Request $request) use($app) { // Create builder $form_builder = $app['form.factory']->createBuilder(); // Set method and action $form_builder->setMethod('post'); $form_builder->setAction($app['url_generator']->generate('about')); // Add input $form_builder->add('name', 'text', array('label' => 'Your name', 'trim' => true, 'max_length' => 50, 'required' => true, 'constraints' => array(new Constraints\NotEqualTo(array('value' => 'f**k', 'message' => 'Be polite you s******d'))))); $form_builder->add('email', 'email', array('label' => 'Your email', 'trim' => true, 'max_length' => 50, 'required' => true));
// Cache $app['cache.path'] = __DIR__ . '/../cache'; // Http cache $app['http_cache.cache_dir'] = $app['cache.path'] . '/http'; $app->register(new SessionServiceProvider()); $app->register(new ValidatorServiceProvider()); $app->register(new FormServiceProvider()); $app->register(new UrlGeneratorServiceProvider()); $app->register(new SwiftmailerServiceProvider(), array('swiftmailer.options' => array('host' => $app['mailer.config.host'], 'port' => $app['mailer.config.port'], 'username' => $app['mailer.config.username'], 'password' => $app['mailer.config.password'], 'encryption' => $app['mailer.config.encryption'], 'auth_mode' => $app['mailer.config.auth_mode']))); /** * It should be placed *BEFORE* TranslationServiceProvider registration */ $app->before(function () use($app) { if ($app['request']->get('locale') && in_array($app['request']->get('locale'), $app['supported_languages'])) { $app['locale'] = $app['request']->get('locale'); } else { return $app->redirect($app['url_generator']->generate('homepage', array('locale' => $app['locale.fallback']))); } }); /** * Services: * * translator: An instance of Translator, that is used for translation. * translator.loader: An instance of an implementation of the translation * LoaderInterface, defaults to an ArrayLoader. * translator.message_selector: An instance of MessageSelector. */ $app->register(new TranslationServiceProvider(), array('locale.fallback' => $app['locale_fallback'])); $app['translator'] = $app->share($app->extend('translator', function ($translator, $app) { $translator->addLoader('yaml', new YamlFileLoader()); $translator->addResource('yaml', __DIR__ . '/../resources/locales/en.yml', 'en');
// Iniciando a sessão $app->register(new Silex\Provider\SessionServiceProvider()); $app['session']->start(); $questions = (include 'questions.php'); // Registrando o Logger de SQL apenas para debug //if ($app['debug']) // $app['db.config']->setSQLLogger(new Log\SilexSkeletonLogger($app['session'], $app['monolog'])); // ================================================== // Filtros (antes e depois das requisições) // ================================================== $app->before(function (Request $request) use($app) { $route = $request->attributes->get('_route'); if (!$app['auth.permission']->freePass($route)) { if (!$app['auth.login']->isAuthenticated()) { return $app->redirect('/login'); } if (!$app['auth.permission']->isAuthorized($route)) { return $app->abort(403, $route . ' - Você não pode acessar esta área!'); } } }); // ================================================== // URL's da Aplicação // ================================================== // ------------ AUTH Example ------------------------ $app->get('/login', function () use($app) { return $app['twig']->render('auth/login.twig', array('error' => '')); })->bind('auth.login'); $app->post('/authenticate', function (Request $request) use($app, $questions) { // Modifique o método getUser() em lib/Auth/Authentication.php $user_name = $request->get('user');
-----------------------------------DATABASE DECLARATION---------------------------------- ---------------------------------------------------------------------------------------*/ include_once "requires/db.php"; /*--------------------------------------------------------------------------------------- ---------------------------------------NAV DEFINITION------------------------------------ ---------------------------------------------------------------------------------------*/ $app['twig'] = $app->share($app->extend('twig', function ($twig) { $twig->addGlobal('nav', array(array("text" => "Home", "url" => "index", "children" => array(array("text" => "Dashboard", "url" => "index"))), array("text" => "Issues", "url" => "issues", "children" => array(array("text" => "Show on hold issues", "url" => "issues", "params" => array("tag" => "on_hold")), array("text" => "Show open issues", "url" => "issues", "params" => array("tag" => "open")), array("text" => "Show resolved issues", "url" => "issues", "params" => array("tag" => "resolved"), "separator" => true), array("text" => "Show latest issues", "url" => "issues", "params" => array("sort_by" => "latest")))))); $twig->addGlobal('timestamp_now', time()); return $twig; })); /*--------------------------------------------------------------------------------------- ----------------------------------------ROUTING NAME------------------------------------- ---------------------------------------------------------------------------------------*/ $app->before(function (Request $request) use($app) { $app['twig']->addGlobal('current_page_name', $request->get("_route")); }); /*--------------------------------------------------------------------------------------- -----------------------------------------INDEX PAGE-------------------------------------- ---------------------------------------------------------------------------------------*/ $app->get('/', function () use($db, $app) { return $app['twig']->render('index.twig', array()); })->bind("index"); /*--------------------------------------------------------------------------------------- -----------------------------------ISSUES LISTING PAGE----------------------------------- ---------------------------------------------------------------------------------------*/ $app->get('/issues/{tag}', function (Request $request, $tag) use($db, $timer, $app) { $counts = array(10, 25, 50, 100, 250, 500); if (null !== $request->query->get('page')) { $start = $request->query->get('page'); } else {
<?php $config = (require_once __DIR__ . '/bootstrap.php'); $app = new Silex\Application(); // production environment - false; test environment - true $app['debug'] = true; //handling CORS preflight request $app->before(function (Symfony\Component\HttpFoundation\Request $request) { if ($request->getMethod() === "OPTIONS") { $response = new \Symfony\Component\HttpFoundation\ResponseHeaderBag(); $response->headers->set("Access-Control-Allow-Origin", "*"); $response->headers->set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); $response->headers->set("Access-Control-Allow-Headers", "Content-Type"); $response->setStatusCode(200); return $response->send(); } }, \Silex\Application::EARLY_EVENT); //handling CORS respons with right headers $app->after(function (Symfony\Component\HttpFoundation\Request $request, Symfony\Component\HttpFoundation\Response $response) { $response->headers->set("Access-Control-Allow-Origin", "*"); $response->headers->set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); }); // setting up json request data $app->before(function (Symfony\Component\HttpFoundation\Request $request) { if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) { $data = json_decode($request->getContent(), true); $request->request->replace(is_array($data) ? $data : array()); } }); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Silex\Provider\DoctrineServiceProvider(), $config['db']);
function getApp() { if (isset($this->_app)) { return $this->_app; } // Initialize out Silex app and let's do it $app = new \Silex\Application(); if ($this->getConfig('twig.debug')) { $app['debug'] = $this->getConfig('twig.debug'); } // Register our session provider $app->register(new \Silex\Provider\SessionServiceProvider()); $app->before(function ($request) use($app) { $app['session']->start(); }); $app['url'] = $this->getConfig('application.url'); $app['uploadPath'] = $this->getConfig('upload.path'); $app['confAirport'] = $this->getConfig('application.airport'); $app['arrival'] = $this->getConfig('application.arrival'); $app['departure'] = $this->getConfig('application.departure'); // Register the Twig provider and lazy-load the global values $app->register(new \Silex\Provider\TwigServiceProvider(), array('twig.path' => APP_DIR . $this->getConfig('twig.template_dir'))); $that = $this; $app['twig'] = $app->share($app->extend('twig', function ($twig, $app) use($that) { $twig->addGlobal('site', array('url' => $that->getConfig('application.url'), 'title' => $that->getConfig('application.title'), 'email' => $that->getConfig('application.email'), 'eventurl' => $that->getConfig('application.eventurl'), 'enddate' => $that->getConfig('application.enddate'))); return $twig; })); // Register our use of the Form Service Provider $app->register(new \Silex\Provider\FormServiceProvider()); $app->register(new \Silex\Provider\ValidatorServiceProvider()); $app->register(new \Silex\Provider\TranslationServiceProvider(), array('translator.messages' => array())); $app['db'] = $this->getDb(); $app['spot'] = $this->getSpot(); $app['purifier'] = $this->getPurifier(); // We're using Sentry, so make it available to app $app['sentry'] = $app->share(function () use($app) { $hasher = new \Cartalyst\Sentry\Hashing\NativeHasher(); $userProvider = new \Cartalyst\Sentry\Users\Eloquent\Provider($hasher); $groupProvider = new \Cartalyst\Sentry\Groups\Eloquent\Provider(); $throttleProvider = new \Cartalyst\Sentry\Throttling\Eloquent\Provider($userProvider); $session = new \OpenCFP\SymfonySentrySession($app['session']); $cookie = new \Cartalyst\Sentry\Cookies\NativeCookie(array()); $sentry = new \Cartalyst\Sentry\Sentry($userProvider, $groupProvider, $throttleProvider, $session, $cookie); \Cartalyst\Sentry\Facades\Native\Sentry::setupDatabaseResolver($app['db']); $throttleProvider->disable(); return $sentry; }); $app['twig'] = $app->share($app->extend('twig', function ($twig, $app) { $twig->addGlobal('user', $app['sentry']->getUser()); return $twig; })); // Configure our flash messages functionality $app->before(function () use($app) { $flash = $app['session']->get('flash'); $app['session']->set('flash', null); if (!empty($flash)) { $app['twig']->addGlobal('flash', $flash); } }); // Add current page global $app->before(function (Request $request) use($app) { $app['twig']->addGlobal('current_page', $request->getRequestUri()); }); // Define error template paths if (!$app['debug']) { $app->error(function (\Exception $e, $code) use($app) { switch ($code) { case 401: $message = $app['twig']->render('error/401.twig'); break; case 403: $message = $app['twig']->render('error/403.twig'); break; case 404: $message = $app['twig']->render('error/404.twig'); break; default: $message = $app['twig']->render('error/500.twig'); } return new Response($message, $code); }); } $app = $this->defineRoutes($app); // Add the starting date for submissions $app['cfpdate'] = $this->getConfig('application.cfpdate'); return $app; }
if (!isset($data->parameters)) { return new Response('Missing parameters.', 400, array('Content-Type' => 'text/json')); } $procedure = "procedure\\" . ucfirst($procedure); if (!class_exists($procedure)) { return new Response('Invalid procedure.', 400, array('Content-Type' => 'text/json')); } $class = new $procedure(); $result = $class->execute($data->parameters); switch ($result['status']) { case 'success': return new Response(json_encode($result['data']), 200); break; case 'error': return new Response('Error executing procedure', 400, array('Content-Type' => 'text/json')); break; } }); $app->before(function (Request $request) use($app) { if (!$request->headers->has('authorization')) { return new Response('Unauthorized', 401); } require_once __DIR__ . '/configs/clients.php'; if (!in_array($request->headers->get('authorization'), array_keys($clients))) { return new Response('Unauthorized', 401); } }); $app->after(function (Request $request, Response $response) { $response->headers->set('Content-Type', 'text/json'); }); $app->run();
require_once __DIR__ . '/../providers/UserProvider.php'; require_once __DIR__ . '/../providers/AdminProvider.php'; require_once __DIR__ . '/../providers/SecurityProvider.php'; $app = new Silex\Application(); $app["debug"] = true; $db = ["driver" => "pdo_mysql", "dbname" => "tickets", "host" => "127.0.0.1", "port" => 3306, "user" => "root", "password" => "123456"]; $sc = ['login' => ['pattern' => '^/login-form'], 'secured' => ['pattern' => '^/user', 'form' => ['login_path' => '/login-form', 'check_path' => '/user/login-save'], 'logout' => ['logout_path' => '/user/logout', 'invalidate_session' => true], 'users' => $app->share(function () use($app) { return new \Tickets\SecurityProvider($app['db']); })]]; $sa = [['^/ticket.+$', 'ROLE_USER'], ['^/user.+$', 'ROLE_USER'], ['^/admin.+$', 'ROLE_ADMIN']]; $app->register(new Silex\Provider\SessionServiceProvider()); $app->register(new Silex\Provider\TwigServiceProvider(), ['twig.path' => __DIR__ . '/../views']); $app->register(new Silex\Provider\DoctrineServiceProvider(), ['db.options' => $db]); $app->register(new Silex\Provider\SecurityServiceProvider(), ['security.firewalls' => $sc, 'security.access_rules' => $sa]); $app->before(function ($request) use($app) { $sh = new \Tickets\SecurityProvider($app["db"]); $app["user"] = $sh->loadUserByUsername($app["session"]->get("username")); }); $app->mount('/ticket', new Tickets\TicketProvider()); $app->mount('/user', new Tickets\UserProvider()); $app->mount('/admin', new Tickets\AdminProvider()); $app->get('/', function () use($app) { $user = isset($app["user"]) ? $app["user"] : null; if ($user == null) { return $app->redirect("/login-form"); } if (array_search('ROLE_ADMIN', $user->getRoles()) !== false) { return $app->redirect("/admin/home"); } if (array_search('ROLE_USER', $user->getRoles()) !== false) { return $app->redirect("/user/home"); }
<?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Validator\Constraints; // Init Silex $app = new Silex\Application(); $app['config'] = $config; $app['debug'] = $config['debug']; // Services $app->register(new Silex\Provider\FormServiceProvider()); $app->register(new Silex\Provider\TranslationServiceProvider()); $app->register(new Silex\Provider\ValidatorServiceProvider()); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => '../app/views')); $app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'pdo_mysql', 'host' => $config['db_host'], 'dbname' => $config['db_name'], 'user' => $config['db_user'], 'password' => $config['db_pass'], 'charset' => 'utf8'))); $app->register(new Silex\Provider\SwiftmailerServiceProvider(), array('swiftmailer.options' => array('host' => 'smtp.gmail.com', 'port' => 465, 'username' => '', 'password' => '', 'encryption' => 'ssl', 'auth_mode' => 'login'))); // Before $app->before(function () use($app) { $app['twig']->addGlobal('title', 'CS-MVC, Light & Powerful'); }); //Object Response $app['db']->setFetchMode(PDO::FETCH_OBJ); //Init Models $articles_model = new Articles_Model($app['db']);
$app->register(new Silex\Provider\SessionServiceProvider()); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Silex\Provider\ValidatorServiceProvider()); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Silex\Provider\TranslationServiceProvider(), array('localefallback' => 'fr')); $app->register(new Silex\Provider\SwiftmailerServiceProvider()); $app->register(new FormServiceProvider()); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => array(__DIR__ . '/../views/app'))); //db $app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'pdo_mysql', 'dbhost' => 'localhost', 'dbname' => 'master', 'user' => 'root', 'password' => ''))); // $app['session.db_options'] = array( // 'db_table' => 'session', // 'db_id_col' => 'session_id', // 'db_data_col' => 'session_value', // 'db_time_col' => 'session_time' // ); // $app['session.storage.handler'] = $app->share(function () use ($app) { // return new PdoSessionHandler( // $app['db']->getWrappedConnection(), // $app['session.db_options'], // $app['session.storage.options'] // ); // }); // Front $frontServiceProvider = new Front\FrontServiceProvider(); $app->register($frontServiceProvider); $app->mount(null, $frontServiceProvider); $app->before(function (Request $request) use($app) { }); $app->boot(); return $app;
$app->register(new Silex\Provider\DoctrineServiceProvider(), ['db.options' => include sprintf('%s/src/Config/credentials.%s.php', BASE_DIR, APP_NAME)]); $app['guzzle'] = $app->share(function () use($app) { return new Guzzle\Http\Client(); }); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Silex\Provider\ValidatorServiceProvider()); $app['home'] = $app->share(function () use($app) { return new Controllers\Home(); }); $app['versions'] = $app->share(function () use($app) { $versions = new Models\Versions($app['db']); return new Controllers\Versions($versions); }); $app->before(function (Request $request, Silex\Application $app) { if (extension_loaded('newrelic')) { newrelic_name_transaction(current(explode('?', $_SERVER['REQUEST_URI']))); } }); $app->after(function (Request $request, Response $response) { $response->headers->set('Access-Control-Allow-Origin', '*'); $response->headers->set('Access-Control-Allow-Methods', 'GET,POST,HEAD,DELETE,PUT,OPTIONS'); $response->headers->set('Access-Control-Allow-Headers', 'Content-Type'); if ($response->getStatusCode() == 200) { $response->headers->set('Content-Type', 'application/json; charset=UTF-8'); } }); $app->match("{url}", function ($url) use($app) { return "OK"; })->assert('url', '.*')->method("OPTIONS"); $app->get('/projects/{project}/latest', 'versions:latest'); $app->get('/', 'home:index');
return new Prontotype\Service\Utils(); }); // pre/post/error handlers $app->before(function () use($app) { $authPage = array($app['uri']->generate('authenticate'), $app['uri']->generate('de_authenticate')); $app['twig']->addGlobal('uri', $app['uri']); $app['twig']->addGlobal('data', $app['data']); $app['twig']->addGlobal('session', $app['session']); $app['twig']->addGlobal('cache', $app['cache']); $app['twig']->addGlobal('pages', $app['pages']); $app['twig']->addGlobal('store', $app['store']); $app['twig']->addGlobal('config', $app['config']); $app['twig']->addGlobal('utils', $app['utils']); $authRequired = !empty($app['config']['authenticate']) && !empty($app['config']['authenticate']['username']) && !empty($app['config']['authenticate']['password']) ? true : false; if (!in_array($app['request']->getRequestUri(), $authPage)) { if ($authRequired) { $currentUser = $app['session']->get($app['config']['prefix'] . 'authed-user'); $userHash = sha1($app['config']['authenticate']['username'] . $app['config']['authenticate']['password']); if (empty($currentUser) || $currentUser !== $userHash) { return $app->redirect($app['uri']->generate('authenticate')); // not logged in, redirect to auth page } } } elseif (!$authRequired) { // redirect visits to the auth pages to the homepage if no auth is required. return $app->redirect('/'); } }); $app->error(function (\Exception $e, $code) use($app) { switch ($code) { case '404':
<?php require 'config.php'; require_once __DIR__ . '/../vendor/autoload.php'; include 'models/snippets.class.php'; $snippets_model = new Snippets_model($pdo); $app = new Silex\Application(); $app['debug'] = true; // Twig $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views')); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); // Used for requests use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; $app->before(function () use($app, $snippets_model) { $categories = $snippets_model->get_categories(); $app["twig"]->addGlobal("categories", $categories); }); $app->get('/', function ($page) use($app, $snippets_model) { $snippets = $snippets_model->get_all(); $pages = $snippets_model->get_pages_all(); $app["twig"]->addGlobal("actualPage", array("page" => "home", "category" => "all")); return $app['twig']->render('snippets.twig', array('snippets' => $snippets, "pages" => $pages)); })->value('page', 1)->bind('home'); $app->get('/category/{category}/{page}', function ($category = "all", $page = 1) use($app, $snippets_model) { if ($category == "all") { $snippets = $snippets_model->get_all($page); $pages = $snippets_model->get_pages_all($page); $cat_details = array('slug' => 'all', 'title' => 'All', 'count' => $snippets_model->get_snippets_count()); } else { $cat_details = $snippets_model->get_cat_details($category); $cat_details = $cat_details[0];
<?php $loader = (require_once __DIR__ . '/../vendor/autoload.php'); define('ROOT_PATH', __DIR__ . '/..'); define('APP_PATH', ROOT_PATH . '/app'); $loader->add('Aixia', ROOT_PATH . '/src'); $app = new Silex\Application(); $app['debug'] = true; $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => array(__DIR__ . '/../app/Resources', __DIR__ . '/../src/Aixia/PostitBoardFront/Resources/views'), 'twig.cache' => array('cache' => __DIR__ . '/../app/cache'))); $app->before(function () use($app) { $app['twig']->addGlobal('layout', $app['twig']->loadTemplate('layout.html.twig')); }); $app['rest.client'] = new \Aixia\PostitBoardFront\RestClient(); $app->get('/postits', function () use($app) { return $app['twig']->render('default.html.twig', ['postits' => $app['rest.client']->get('postits')]); })->bind('homepage'); $app->get('/', function () use($app) { return $app->redirect('/postits'); }); $app->match('/edit/{id}', function (\Symfony\Component\HttpFoundation\Request $request) use($app) { $id = $request->get('id'); if ($request->isMethod('POST')) { $message = $request->get('message'); $app['rest.client']->patch('postits', $id, ['post_it' => ['message' => utf8_encode($message)]]); } $res = $app['rest.client']->get('postits', $id); return $app['twig']->render('edit.html.twig', ['postit' => $res]); })->bind('edit'); $app->match('/new', function (\Symfony\Component\HttpFoundation\Request $request) use($app) { if ($request->isMethod('POST')) { $message = $request->get('message');
require_once __DIR__ . '/../vendor/autoload.php'; define('GOOGLE_API_KEY', '389361308386-0lc02qa6gs3q0pf7j86hhj169to93jh9.apps.googleusercontent.com'); define('GOOGLE_API_SECRET', 'nijEu5O05kXBLQv9pawzrF9Z'); $app = new Silex\Application(); error_reporting(E_ALL); ini_set('display_errors', 1); $app['debug'] = true; $app->register(new Gigablah\Silex\OAuth\OAuthServiceProvider(), array('oauth.services' => array('Google' => array('key' => GOOGLE_API_KEY, 'secret' => GOOGLE_API_SECRET, 'scope' => array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'), 'user_endpoint' => 'https://www.googleapis.com/oauth2/v1/userinfo')))); // Provides URL generation $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); // Provides CSRF token generation $app->register(new Silex\Provider\FormServiceProvider()); // Provides session storage $app->register(new Silex\Provider\SessionServiceProvider(), array('session.storage.save_path' => __DIR__ . '/../cache')); // Provides Twig template engine $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__)); $app->register(new Silex\Provider\SecurityServiceProvider(), array('security.firewalls' => array('default' => array('pattern' => '^/', 'anonymous' => true, 'oauth' => array('failure_path' => '/', 'with_csrf' => true), 'logout' => array('logout_path' => '/logout', 'with_csrf' => true), 'users' => new Gigablah\Silex\OAuth\Security\User\Provider\OAuthInMemoryUserProvider())), 'security.access_rules' => array(array('^/auth', 'ROLE_USER')))); $app->before(function (Symfony\Component\HttpFoundation\Request $request) use($app) { $token = $app['security']->getToken(); $app['user'] = null; if ($token && !$app['security.trust_resolver']->isAnonymous($token)) { $app['user'] = $token->getUser(); } }); $app->get('/', function () use($app) { return $app['twig']->render('index.twig', array('login_paths' => $app['oauth.login_paths'], 'logout_path' => $app['url_generator']->generate('logout', array('_csrf_token' => $app['oauth.csrf_token']('logout'))))); }); $app->match('/logout', function () { })->bind('logout'); $app->run();
define("SRC_DIR", __DIR__ . "/../src/"); define("PUBLIC_DIR", __DIR__); $app = new \Silex\Application(); $app['conf'] = (require SRC_DIR . "Config/Config.php"); $app['debug'] = $app['conf']['app.environment'] == 'development' ? true : false; if ($app['debug']) { $app->register(new \Whoops\Provider\Silex\WhoopsServiceProvider()); $app->register(new \Dongww\Silex\Provider\DebugBarServiceProvider()); $app->register(new \Silex\Provider\TwigServiceProvider(), array('twig.path' => SRC_DIR . 'Templates', 'twig.options' => ['cache' => false, 'optimizations' => 0])); } else { $app->register(new \Silex\Provider\TwigServiceProvider(), array('twig.path' => SRC_DIR . 'Templates', 'twig.options' => ['cache' => $app['conf']['app.layout.cache'], 'optimizations' => -1])); } $app->register(new \Silex\Provider\ServiceControllerServiceProvider()); $app->register(new \Silex\Provider\SessionServiceProvider()); $app->before(function ($request) { $request->getSession()->start(); }); /** * Redis Session Provider * ---------------------- * Replace built-in PHP Session backend with redis */ $app->register(new \Predis\Silex\ClientsServiceProvider(), array('predis.clients' => array('db' => 'tcp://' . $app['conf']['app.redis.host'], 'session' => array('parameters' => 'tcp://' . $app['conf']['app.redis.host'], 'options' => array('prefix' => $app['conf']['app.redis.prefix'] . ':'))))); $app->register(new \Silex\Provider\SessionServiceProvider(), array('session.storage.handler' => $app->share(function () use($app) { $client = $app['predis']['session']; $options = array('gc_maxlifetime' => 300); $handler = new \Predis\Session\Handler($client, $options); return $handler; }))); /** * Dependency Injection