php Silex-Application类(方法)实例源码

下面列出了php Silex-Application 类(方法)源码代码实例,从而了解它的用法。

作者:tesme    项目:tesmen.c   
public function register(Application $app)
 {
     $app['stack'] = $app->share(function ($app) {
         $stack = new Stack($app);
         return $stack;
     });
 }

作者:apitud    项目:apitud   
/**
  * Automatically registers all service classes in $this->services array
  * {@inheritdoc}
  * @param Application|\Apitude\Core\Application $app
  */
 public function register(Application $app)
 {
     foreach ($this->services as $key => $class) {
         if (is_numeric($key)) {
             $key = $class;
         }
         $app[$key] = $app->share(function () use($class, $app) {
             $result = new $class();
             $app->initialize($result);
             return $result;
         });
     }
     if (!empty($this->doctrineEventSubscribers)) {
         $config = $app['config'];
         foreach ($this->doctrineEventSubscribers as $class) {
             $config['orm.subscribers'][] = $class;
         }
     }
     if (!empty($this->entityFolders)) {
         if (!isset($config)) {
             $config = $app['config'];
         }
         foreach ($this->entityFolders as $namespace => $path) {
             $config['orm.options']['orm.em.options']['mappings'][] = ['type' => 'annotation', 'namespace' => $namespace, 'path' => $path, 'use_simple_annotation_reader' => false];
         }
     }
     if (isset($config)) {
         $app['config'] = $config;
     }
     if (php_sapi_name() === 'cli' && !empty($this->commands)) {
         $app['base_commands'] = $app->extend('base_commands', function (array $commands) {
             return array_merge($commands, $this->commands);
         });
     }
 }

作者:shomim    项目:builde   
public function register(Application $app)
 {
     $app['translator'] = $app->share(function ($app) {
         $translator = new Translator($app, $app['translator.message_selector'], $app['translator.cache_dir'], $app['debug']);
         // Handle deprecated 'locale_fallback'
         if (isset($app['locale_fallback'])) {
             $app['locale_fallbacks'] = (array) $app['locale_fallback'];
         }
         $translator->setFallbackLocales($app['locale_fallbacks']);
         $translator->addLoader('array', new ArrayLoader());
         $translator->addLoader('xliff', new XliffFileLoader());
         foreach ($app['translator.domains'] as $domain => $data) {
             foreach ($data as $locale => $messages) {
                 $translator->addResource('array', $messages, $locale, $domain);
             }
         }
         return $translator;
     });
     $app['translator.message_selector'] = $app->share(function () {
         return new MessageSelector();
     });
     $app['translator.domains'] = array();
     $app['locale_fallbacks'] = array('en');
     $app['translator.cache_dir'] = null;
 }

作者:mrpromp    项目:silex-soundclou   
/**
  * (non-PHPdoc)
  * @see \Silex\ServiceProviderInterface::register()
  * @param Application $app
  */
 public function register(Application $app)
 {
     $service = $this;
     $app[static::NAME] = $app->protect(function (string $url) use($service) {
         return $service->create($url);
     });
 }

作者:mrpromp    项目:silex-passwor   
/**
  * Bootstrap
  */
 public function setUp()
 {
     parent::setUp();
     $app = new Application();
     $app->register(new Password(self::DEFAULT_COST));
     $this->app = $app;
 }

作者:neemz    项目:patchwork-cor   
/**
  * Silex method that exposes routes to the app
  *
  * @param Silex\Application $app Application instance
  *
  * @return Silex\ControllerCollection Object encapsulating crafted routes
  */
 public function connect(Application $app)
 {
     $ctrl = $app['controllers_factory'];
     /**
      * Homepage
      */
     $ctrl->get('/', function () use($app) {
         $root = str_replace('index.php/', '', $app['url_generator']->generate('home'));
         if ($app['request']->getRequestURI() != $root) {
             return $app->redirect($root, Response::HTTP_MOVED_PERMANENTLY);
         }
         return $app['twig']->render('front/partials/home.twig');
     })->bind('home');
     /**
      * Admin root
      */
     $ctrl->get('/admin', function () use($app) {
         return $app->redirect($app['url_generator']->generate($app['config']['admin']['root']));
     });
     /**
      * robots.txt
      */
     $ctrl->get('/robots.txt', function () use($app) {
         $response = new Response('User-agent: *' . PHP_EOL . ($app['debug'] ? 'Disallow: /' : 'Sitemap: ' . $app['url_generator']->generate('home') . 'sitemap.xml'));
         $response->headers->set('Content-Type', 'text/plain');
         return $response;
     });
     return $ctrl;
 }

作者:willianman    项目:minicurso_phpconference201   
public function register(Application $app)
 {
     $this->app = $app;
     $app['session.test'] = false;
     $app['session'] = $app->share(function ($app) {
         if (!isset($app['session.storage'])) {
             if ($app['session.test']) {
                 $app['session.storage'] = $app['session.storage.test'];
             } else {
                 $app['session.storage'] = $app['session.storage.native'];
             }
         }
         return new Session($app['session.storage']);
     });
     $app['session.storage.handler'] = $app->share(function ($app) {
         return new NativeFileSessionHandler($app['session.storage.save_path']);
     });
     $app['session.storage.native'] = $app->share(function ($app) {
         return new NativeSessionStorage($app['session.storage.options'], $app['session.storage.handler']);
     });
     $app['session.storage.test'] = $app->share(function () {
         return new MockFileSessionStorage();
     });
     $app['session.storage.options'] = array();
     $app['session.default_locale'] = 'en';
     $app['session.storage.save_path'] = null;
 }

作者:jkaa    项目:timOnlineBol   
public function register(Application $app)
 {
     $app['schema'] = $app->share(function ($app) {
         return new Manager($app);
     });
     $app['schema.tables'] = $app->share(function (Application $app) {
         /** @var \Doctrine\DBAL\Platforms\AbstractPlatform $platform */
         $platform = $app['db']->getDatabasePlatform();
         return new \Pimple(['authtoken' => $app->share(function () use($platform) {
             return new Table\AuthToken($platform);
         }), 'cron' => $app->share(function () use($platform) {
             return new Table\Cron($platform);
         }), 'log_change' => $app->share(function () use($platform) {
             return new Table\LogChange($platform);
         }), 'log_system' => $app->share(function () use($platform) {
             return new Table\LogSystem($platform);
         }), 'relations' => $app->share(function () use($platform) {
             return new Table\Relations($platform);
         }), 'taxonomy' => $app->share(function () use($platform) {
             return new Table\Taxonomy($platform);
         }), 'users' => $app->share(function () use($platform) {
             return new Table\Users($platform);
         })]);
     });
 }

作者:ygeneration66    项目:e   
public function __construct(SilexApplication $application, $projectDirectory, $name = 'UNKNOWN', $version = 'UNKNOWN')
 {
     parent::__construct($name, $version);
     $this->silexApplication = $application;
     $this->projectDirectory = $projectDirectory;
     $application->boot();
 }

作者:Thomthomar    项目:es-solutio   
/**
  * @param \Silex\Application $app
  * This function can return listing of node.
  */
 public function show(Application $app)
 {
     header("Content-Type: text/html; charset=UTF-8");
     $client = $app['elasticsearch'];
     $search = $_GET['recherche'];
     $params['index'] = 'elasticsearch_index_csoecsic_content';
     $params['type'] = 'content';
     $ret = $client->indices()->getMapping(array('index' => 'elasticsearch_index_csoecsic_content'));
     $params['body']['query']['match']['_all'] = $search;
     $result = $client->search($params);
     // If no result from node Elasticsearch.
     if ($result && $result['hits']['total'] === 0) {
         $app->abort(404, sprintf('Node %s does not exist.', $search));
     }
     // If result from node Elasticsearch.
     if ($result['hits']['total'] > 0) {
         $nodes = $result['hits']['hits'];
     } else {
         print 'no result for this search';
     }
     $output['title_doc'] = 'Le contenu le plus pertinent :' . $nodes[0]['_source']['title'] . '';
     $output['score'] = 'Le meilleurs résultat de la recherche est :' . $nodes[0]['_score'] . '';
     //return '<p>Le contenu le plus pertinent :' . $nodes[0]['_source']['title'] . '</p>' . '<p>Avec comme score :' . $nodes[0]['_score'] . '</p>';
     /*return $app->render('template/result.php', array('node' => reset($output)));*/
     return $app['twig']->render('index.html.twig', ['result' => $output]);
 }

作者:robertkrai    项目:bol   
public function register(Application $app)
 {
     $app['log'] = $app->share(function ($app) {
         $log = new Bolt\Log($app);
         return $log;
     });
 }

作者:selmanoun    项目:ip2local   
/**
  * Registers services on the given app.
  *
  * This method should only be used to configure services and parameters.
  * It should not get services.
  *
  * @param Application $app An Application instance
  */
 public function register(Application $app)
 {
     if (!isset($app['locales_allowed'])) {
         throw new \RuntimeException('No locales are specified in your config');
     }
     if (!isset($app['em'])) {
         throw new \RuntimeException('No entity manager has been settled');
     }
     if (!isset($app['ip2locale.ip2country_manager'])) {
         $app['ip2locale.ip2country_manager'] = $app->share(function () use($app) {
             return new IP2CountryManager($app['em']);
         });
     }
     if (isset($app['ip2locale.ip2country_manager_enabled'])) {
         $app['ip2locale.ip2country_manager']->setEnabled($app['ip2locale.ip2country_manager_enabled']);
     }
     if (isset($app['ip2locale.ipv6_enabled'])) {
         $app['ip2locale.ip2country_manager']->setIpv6Enabled($app['ip2locale.ipv6_enabled']);
     }
     if (!isset($app['ip2locale.language_detector'])) {
         $app['ip2locale.language_detector'] = $app->share(function () use($app) {
             return new LanguageDetector();
         });
     }
     if (isset($app['ip2locale.language_detector_enabled'])) {
         $app['ip2locale.language_detector']->setEnabled($app['ip2locale.language_detector_enabled']);
     }
     if (!isset($app['ip2locale.locator'])) {
         $app['ip2locale.locator'] = $app->share(function () use($app) {
             return new IPLocator($app['ip2locale.ip2country_manager'], $app['ip2locale.language_detector'], $app['locales_allowed']);
         });
     }
 }

作者:romainneutro    项目:Phraseane   
public function register(Application $app)
 {
     $app['task-manager.logger'] = $app->share(function (Application $app) {
         $logger = new $app['monolog.logger.class']('task-manager logger');
         $logger->pushHandler(new NullHandler());
         return $logger;
     });
     $app['task-manager'] = $app->share(function (Application $app) {
         $options = $app['task-manager.listener.options'];
         $manager = TaskManager::create($app['dispatcher'], $app['task-manager.logger'], $app['task-manager.task-list'], ['listener_protocol' => $options['protocol'], 'listener_host' => $options['host'], 'listener_port' => $options['port'], 'tick_period' => 1]);
         $manager->addSubscriber($app['ws.task-manager.broadcaster']);
         return $manager;
     });
     $app['task-manager.logger.configuration'] = $app->share(function (Application $app) {
         $conf = array_replace(['enabled' => true, 'level' => 'INFO', 'max-files' => 10], $app['conf']->get(['main', 'task-manager', 'logger'], []));
         $conf['level'] = defined('Monolog\\Logger::' . $conf['level']) ? constant('Monolog\\Logger::' . $conf['level']) : Logger::INFO;
         return $conf;
     });
     $app['task-manager.task-list'] = $app->share(function (Application $app) {
         $conf = $app['conf']->get(['registry', 'executables', 'php-conf-path']);
         $finder = new PhpExecutableFinder();
         $php = $finder->find();
         return new TaskList($app['EM']->getRepository('Phraseanet:Task'), $app['root.path'], $php, $conf);
     });
 }

作者:nachoner    项目:silex-markdown-provide   
/**
  * Register
  *
  * @param Application $app [description]
  *
  * @return void
  */
 public function register(Application $app)
 {
     $app['nn.markdown'] = $app->share(function () {
         return new Markdown();
     });
     if (isset($app["twig"])) {
         $app['twig'] = $app->share($app->extend('twig', function (\Twig_Environment $twig, Application $app) {
             $filterParse = new \Twig_SimpleFilter('markdown_parse', function ($text) use($app) {
                 return $app['nn.markdown']->parse($text);
             }, array('is_safe' => array('html')));
             $twig->addFilter($filterParse);
             $filterParseFile = new \Twig_SimpleFilter('markdown_parse_file', function ($filename) use($app) {
                 return $app['nn.markdown']->parseFile($filename);
             }, array('is_safe' => array('html')));
             $fucntionParseLastFile = new \Twig_SimpleFunction('markdown_parse_last_file', function () use($app) {
                 $content = "";
                 $finderLast = $app['nn.markdown']->getNLastFiles(1);
                 foreach ($finderLast as $file) {
                     $content = $file->getContents();
                 }
                 return $app['nn.markdown']->parse($content);
             }, array('is_safe' => array('html')));
             $twig->addFilter($filterParse);
             $twig->addFilter($filterParseFile);
             $twig->addFunction($fucntionParseLastFile);
             return $twig;
         }));
     }
 }

作者:syntropysoftwar    项目:cryptoffice-fronten   
protected function checkRouteResponse(Application $app, $path, $expectedContent, $method = 'get', $message = null)
 {
     $app->register(new ServiceControllerServiceProvider());
     $request = Request::create($path, $method);
     $response = $app->handle($request);
     $this->assertEquals($expectedContent, $response->getContent(), $message);
 }

作者:radical-assembl    项目:OpenACalendar-Web-Cor   
protected function build($siteid, $slug, Request $request, Application $app)
 {
     $this->parameters = array('user' => null, 'eventCreated' => null, 'eventDupe' => null);
     $sr = new SiteRepository();
     $this->parameters['site'] = $sr->loadById($siteid);
     if (!$this->parameters['site']) {
         $app->abort(404);
     }
     $repo = new NewEventDraftRepository();
     $this->parameters['draft'] = $repo->loadBySlugForSite($slug, $this->parameters['site']);
     if (!$this->parameters['draft']) {
         $app->abort(404);
     }
     if ($this->parameters['draft']->getUserAccountId()) {
         $ur = new UserAccountRepository();
         $this->parameters['user'] = $ur->loadByID($this->parameters['draft']->getUserAccountId());
     }
     if ($this->parameters['draft']->getEventId()) {
         $er = new EventRepository();
         $this->parameters['eventCreated'] = $er->loadByID($this->parameters['draft']->getEventId());
     }
     if ($this->parameters['draft']->getWasExistingEventId()) {
         $er = new EventRepository();
         $this->parameters['eventDupe'] = $er->loadByID($this->parameters['draft']->getWasExistingEventId());
     }
 }

作者:TiberiuGa    项目:sg   
public function contactSentAction(Request $request, Application $app)
 {
     $data = $request->get('contact_form');
     $configData = $app['configs']->getData();
     $contactEmails = $configData['contact_email'] ? explode(',', $configData['contact_email']) : array('secretariat@scoalachristiana.ro');
     $message = sprintf('
         Salut,
                 Ai primit un mesaj prin intermediul formularului de contact.
                 Mesaj: %s.
                 Primit la %s  de la %s cu adresa %s.', $data['mesaj'], date('d-m-Y H:i'), $data['nume'], $data['email']);
     $mailer = $app['mailer'];
     $mailer->isSMTP();
     $mailer->Host = 'localhost';
     //$mailer->Username = '';
     //$mailer->Password = '';
     //$mailer->SMTPSecure = 'ssl';
     $mailer->Port = 25;
     $mailer->setFrom('no-reply@scoalachristiana.ro');
     $mailer->addReplyTo($data['email']);
     foreach ($contactEmails as $email) {
         $mailer->addAddress($email);
     }
     $mailer->Subject = 'Formular contact ';
     $mailer->Body = $message;
     $mailer->send();
     $_SESSION['message_sent'] = TRUE;
     return $app->redirect('/contact', 302);
 }

作者:philipl    项目:crudlexuse   
public static function createAppAndDB($useManyToMany)
 {
     $app = new Application();
     $app->register(new DoctrineServiceProvider(), ['dbs.options' => ['default' => ['host' => '127.0.0.1', 'dbname' => 'crudTest', 'user' => 'root', 'password' => '', 'charset' => 'utf8']]]);
     $app['db']->executeUpdate('DROP TABLE IF EXISTS password_reset;');
     $app['db']->executeUpdate('DROP TABLE IF EXISTS user_role;');
     $app['db']->executeUpdate('DROP TABLE IF EXISTS role;');
     $app['db']->executeUpdate('DROP TABLE IF EXISTS user;');
     $app['db']->executeUpdate('SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";');
     $app['db']->executeUpdate('SET time_zone = "+00:00"');
     $sql = 'CREATE TABLE `role` (' . '  `id` int(11) NOT NULL AUTO_INCREMENT,' . '  `version` int(11) NOT NULL,' . '  `created_at` datetime NOT NULL,' . '  `updated_at` datetime NOT NULL,' . '  `deleted_at` datetime DEFAULT NULL,' . '  `role` varchar(255) NOT NULL,' . '  PRIMARY KEY (`id`)' . ') ENGINE=InnoDB DEFAULT CHARSET=utf8;';
     $app['db']->executeUpdate($sql);
     $sql = 'CREATE TABLE `user` (' . '  `id` int(11) NOT NULL AUTO_INCREMENT,' . '  `created_at` datetime NOT NULL,' . '  `updated_at` datetime NOT NULL,' . '  `deleted_at` datetime DEFAULT NULL,' . '  `version` int(11) NOT NULL,' . '  `password` varchar(255) NOT NULL,' . '  `salt` varchar(255) NOT NULL,' . '  `username` varchar(255) NOT NULL,' . '  `email` varchar(255) NOT NULL,' . '  PRIMARY KEY (`id`)' . ') ENGINE=InnoDB DEFAULT CHARSET=utf8;';
     $app['db']->executeUpdate($sql);
     if ($useManyToMany) {
         $sql = 'CREATE TABLE `user_role` (' . '  `user` int(11) NOT NULL,' . '  `role` int(11) NOT NULL,' . '  KEY `user` (`user`),' . '  KEY `role` (`role`),' . '  CONSTRAINT `userrole_ibfk_1` FOREIGN KEY (`user`) REFERENCES `user` (`id`),' . '  CONSTRAINT `userrole_ibfk_2` FOREIGN KEY (`role`) REFERENCES `role` (`id`)' . ') ENGINE=InnoDB DEFAULT CHARSET=utf8;';
         $app['db']->executeUpdate($sql);
     } else {
         $sql = 'CREATE TABLE `user_role` (' . '  `id` int(11) NOT NULL AUTO_INCREMENT,' . '  `version` int(11) NOT NULL,' . '  `created_at` datetime NOT NULL,' . '  `updated_at` datetime NOT NULL,' . '  `deleted_at` datetime DEFAULT NULL,' . '  `user` int(11) NOT NULL,' . '  `role` int(11) NOT NULL,' . '  PRIMARY KEY (`id`),' . '  KEY `user` (`user`),' . '  KEY `role` (`role`),' . '  CONSTRAINT `userrole_ibfk_1` FOREIGN KEY (`user`) REFERENCES `user` (`id`),' . '  CONSTRAINT `userrole_ibfk_2` FOREIGN KEY (`role`) REFERENCES `role` (`id`)' . ') ENGINE=InnoDB DEFAULT CHARSET=utf8;';
         $app['db']->executeUpdate($sql);
     }
     $sql = 'CREATE TABLE `password_reset` (' . '  `id` int(11) NOT NULL AUTO_INCREMENT,' . '  `version` int(11) NOT NULL,' . '  `created_at` datetime NOT NULL,' . '  `updated_at` datetime NOT NULL,' . '  `deleted_at` datetime DEFAULT NULL,' . '  `user` int(11) NOT NULL,' . '  `token` varchar(255) NOT NULL,' . '  `reset` datetime DEFAULT NULL,' . '  PRIMARY KEY (`id`),' . '  KEY `user` (`user`),' . '  CONSTRAINT `passwordreset_ibfk_1` FOREIGN KEY (`user`) REFERENCES `user` (`id`)' . ') ENGINE=InnoDB DEFAULT CHARSET=utf8;';
     $app['db']->executeUpdate($sql);
     return $app;
 }

作者:nlegof    项目:Phraseane   
/**
  * {@inheritDoc}
  */
 public function boot(Application $app)
 {
     $app['dispatcher'] = $app->share($app->extend('dispatcher', function ($dispatcher, Application $app) {
         $dispatcher->addSubscriber(new XSendFileSubscriber($app));
         return $dispatcher;
     }));
 }

作者:nlegof    项目:Phraseane   
/**
  * Get record detailed view
  *
  * @param Application $app
  * @param Request     $request
  *
  * @return JsonResponse
  */
 public function getRecord(Application $app, Request $request)
 {
     if (!$request->isXmlHttpRequest()) {
         $app->abort(400);
     }
     $searchEngine = $options = null;
     $train = '';
     if ('' === ($env = strtoupper($request->get('env', '')))) {
         $app->abort(400, '`env` parameter is missing');
     }
     // Use $request->get as HTTP method can be POST or GET
     if ('RESULT' == ($env = strtoupper($request->get('env', '')))) {
         try {
             $options = SearchEngineOptions::hydrate($app, $request->get('options_serial'));
             $searchEngine = $app['phraseanet.SE'];
         } catch (\Exception $e) {
             $app->abort(400, 'Search-engine options are not valid or missing');
         }
     }
     $pos = (int) $request->get('pos', 0);
     $query = $request->get('query', '');
     $reloadTrain = !!$request->get('roll', false);
     $record = new \record_preview($app, $env, $pos < 0 ? 0 : $pos, $request->get('cont', ''), $searchEngine, $query, $options);
     if ($record->is_from_reg()) {
         $train = $app['twig']->render('prod/preview/reg_train.html.twig', ['record' => $record]);
     }
     if ($record->is_from_basket() && $reloadTrain) {
         $train = $app['twig']->render('prod/preview/basket_train.html.twig', ['record' => $record]);
     }
     if ($record->is_from_feed()) {
         $train = $app['twig']->render('prod/preview/feed_train.html.twig', ['record' => $record]);
     }
     return $app->json(["desc" => $app['twig']->render('prod/preview/caption.html.twig', ['record' => $record, 'highlight' => $query, 'searchEngine' => $searchEngine, 'searchOptions' => $options]), "html_preview" => $app['twig']->render('common/preview.html.twig', ['record' => $record]), "others" => $app['twig']->render('prod/preview/appears_in.html.twig', ['parents' => $record->get_grouping_parents(), 'baskets' => $record->get_container_baskets($app['EM'], $app['authentication']->getUser())]), "current" => $train, "history" => $app['twig']->render('prod/preview/short_history.html.twig', ['record' => $record]), "popularity" => $app['twig']->render('prod/preview/popularity.html.twig', ['record' => $record]), "tools" => $app['twig']->render('prod/preview/tools.html.twig', ['record' => $record]), "pos" => $record->get_number(), "title" => str_replace(['[[em]]', '[[/em]]'], ['<em>', '</em>'], $record->get_title($query, $searchEngine))]);
 }


问题


面经


文章

微信
公众号

扫码关注公众号