Giter Site home page Giter Site logo

silexphp / silex Goto Github PK

View Code? Open in Web Editor NEW
3.6K 202.0 727.0 3.58 MB

[DEPRECATED -- Use Symfony instead] The PHP micro-framework based on the Symfony Components

Home Page: https://silex.symfony.com

License: MIT License

PHP 100.00%
php silex framework symfony

silex's Introduction

Silex, a simple Web Framework

WARNING: Silex is in maintenance mode only. Ends of life is set to June 2018. Read more on Symfony's blog.

Silex is a PHP micro-framework to develop websites based on Symfony components:

Silex works with PHP 7.1.3 or later.

Installation

The recommended way to install Silex is through Composer:

Alternatively, you can download the silex.zip file and extract it.

More Information

Read the documentation for more information and changelog for upgrading information.

Tests

To run the test suite, you need Composer and PHPUnit:

Support

If you have a configuration problem use the silex tag on StackOverflow to ask a question.

If you think there is an actual problem in Silex, please open an issue if there isn't one already created.

License

Silex is licensed under the MIT license.

silex's People

Contributors

ad7six avatar alexkappa avatar benoitpointet avatar brtriver avatar cordoval avatar danez avatar davedevelopment avatar fabpot avatar gromnan avatar henrikbjorn avatar hkdobrev avatar igorw avatar jdreesen avatar jeroendedauw avatar jmontoyaa avatar laurent35240 avatar lyrixx avatar nicoder avatar ragboyjr avatar ricardclau avatar romainneutron avatar seldaek avatar skalpa avatar sofhad avatar spacepossum avatar stof avatar tobion avatar umpirsky avatar vicb avatar wouterj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

silex's Issues

Session does not start in "before" filter.

Now I use this:

$app->before(function ($request) use ($app) {

    $request->setSession($app['session']);
    if ($request->hasPreviousSession()) {
        $request->getSession()->start();
    };
    ...
};

Session throws errors

This code yields a header already sent error on every new browser launch (tested in chrome/ff on osx)

require_once __DIR__.'/silex.phar'; 
use Silex\Application; 
use Silex\Extension\SessionExtension; 
$app = new Application(); 
$app->register(new Silex\Extension\SessionExtension()); 

$app->get('/', function () { 
return 'hello'; 
}); 

You need to call $app['session']->start(); before the routes are defined - it seems the session calls start after the routes and therefore error happens (only on initial browser launch). Perhaps docs need to mention that.

DoctrineExtension Documentation (Need a Note?)

  1. The documentation for the DoctrineExtension doesn't have a note that you'll need to download the two libraries separate from Silex. I only notice it didn't say this because the TwigExtension documentation does.
  2. The DBAL project (if you init with a submodule) comes with doctrine-common. So I would think another note about a possible setup using submodules so there isn't duplicate code in a "small" project.

Here's the code I used once I initialized my submodules for the DoctrineExetension.
$app->register(new DoctrineExtension(), array( 'db.options' => array( 'dbname' => 'db_name', 'host' => 'localhost', 'user' => 'root', 'password' => '1234', ), 'db.dbal.class_path' => __DIR__.'/../vendors/doctrine-dbal/lib', 'db.common.class_path' => __DIR__.'/../vendors/doctrine-dbal/lib/vendor/doctrine-common/lib', ));

Something to keep in mind with my project, I have created a web folder so that my vendors folder isn't web accessible.

Thanks for your time,
Jarvis

Separate container from application

This proposal is kind of inspired by #155. Since that PR decouples the registering of routes from the application, we could do the same thing with the container. I understand that some of these changes are going a bit far, so please share your thoughts. As always, it's a fine line. ;)

Right now the application extends Pimple, so the app is the container. This makes the container heavier, and ties your app to that particular container. Here is my idea.

First of all, we namespace pimple properly. So the Pimple class will become Pimple\Container. The reason for this is that I would then like to introduce a few more classes. One is the Pimple\ContainerInterface which is implemented by all containers. The next is a Pimple\ContainerWrapper which implements said interface and takes an actual container as a setter argument, proxying all the calls to the member container.

Now the silex application can extend the ContainerWrapper, allowing you to give it any container, by default it just creates one. This means you are a lot more flexible with re-using your container.

Another thing is that we have a wide range of Silex extensions that really only use the container. So having a Pimple\ExtensionInterface could be interesting as well, allowing those extensions to be even more re-usable, outside of Silex (just with pimple itself).

While most of these proposed changes are for the pimple code base, it makes more sense to discuss them here. Please let me know if this idea is stupid, too complex, or maybe even feasible. Thanks!

[docs] Cookbook

It would be great to have a cookbook with some recipes.

  • Authentication (and Users)
  • File upload
  • Matching full paths (discussion)
  • AJAX requests in WebTestCase (discussion)
  • overriding services
  • integrating libraries / Symfony2 bundles

Please suggest more.

Unable to load Twig using TwigExtension

Using the extension method to get Twig renders a php error:

Fatal error: Class 'Twig_Environment' not found in phar:///Users/rdohms/dev/swat/server_tools/deployer/library/vendor/silex.phar/src/Silex/Extension/TwigExtension.php on line 12

Looking at TwigExtension it first calls Twig_Environment and only at the end does it actually register the namespace for it. Am I doing something wrong or is this the wrong way around, using this to register exception:

    $app->register(new TwigExtension(), array(
        'twig.path'    => TPL_PATH,
        'twig.class_path'   => LIB_PATH . 'silex.phar/vendor/twig/lib/',
    ));

Unable to set the Swiftmailer Transport

I wanted to use the Null Transporter in my tests, however I was unable to set this.

Looking at the SwiftmailerExtension it seems that the Transport is always Swift_Transport_EsmtpTransport?

Is this correct?

Updating to latest Symfony now requires php5-intl

@fabpot: Thanks for updating to the latest Symfony today. During testing I got an exception and the solution might be included in the documentation (i.e. required PHP extensions):

Fatal error: Class 'Locale' not found in phar:///srv/www/iplant.local/htdocs/Library/silex.phar/vendor/Symfony/Component/HttpFoundation/Session.php on line 188

This is solved by installing:

  • On Ubuntu: php5-intl
  • On RHEL/CentOS: php-intl

Reusing applications makes redirects awkward

If I make an application and mount it to another application with a prefix, any self referencing redirects used get wonky.

For example:
https://gist.github.com/984253

I understand the reason this fails as redirects do not care about the application context.

However if reusable applications are a goal of Silex I think being able to handle redirects in a way that could allow them to be modified would be ideal. Perhaps maybe we could have a method of redirection to a named route (this does not allow for variable passing however)?

Thoughts? Or am I missing something REALLY obvious?

The example I made is VERY simple implementation and not a good use of the framework but I wanted to demonstrate the awkwardness as simply as possible.

Form validation not working

Built in form validation using $form->isValid() fails by always returning true. I have the static loadValidatorMetadata() method in a plain Php model class. A workaround like this works, though:

$violations = $app['validator']->validate($person);

The full route is this (I manually inject the violations back into the proper form fields; what a hack!):

$app->post('/register/save', function() use ($app) {
    $person = new Entities\Person();

    $action = $app['url_generator']->generate('save_registration');
    $form = $app['form.factory']->createBuilder(new Entities\Person\PersonForm(), $person, array('csrf_protection' => false))->getForm();
    $request = $app['request'];

    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);
        $form_elements = $form->getChildren();
        $violations = $app['validator']->validate($person);
        $count_of_violations = $violations->count();

        if ( empty($count_of_violations) ) { //$form->isValid() doesn't work yet...
            $data = $form->getData();

            $app['doctrine.orm.em']->persist($person);
            $app['doctrine.orm.em']->flush();

            /* implement post-redirect-get pattern */
            return $app->redirect('/register/complete');
        } else {
            // render the template with the errors, because it doesn't work on its own right now!
            foreach ( $form_elements as $element ) {
                foreach ( $violations as $error ) {
                    $error_name = $error->getPropertyPath();
                    $form_element_name = $element->getName();
                    if ( $error_name === $form_element_name ) {
                        $element->addError(new FormError($violations[0]->getMessage()));
                    }
                }
            }

            return $app['twig']->render('registration/form.phtml', array('form' => $form->createView(), 'action' => $action));
        }
    }

    return $app['twig']->render('registration/form.phtml', array('form' => $form->createView(), 'action' => $action));
}, "GET|POST")->bind('save_registration');

The model is this:

namespace Entities;

//use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @Entity
 * @Table(name="people")
 */
class Person {
    /**
     * @Id
     * @Column(name="id", type="integer", nullable=false))
     * @GeneratedValue
     */
    private $id;

    /**
     * @Column(name="first_name", type="string", length=64)
     * @Assert\NotBlank()
     * @Assert\MinLength(2)
     * @Assert\MaxLength(64)
     */
    private $firstname;

    /**
     * @Column(name="last_name", type="string", length=64)
     * @Assert\NotBlank()
     * @Assert\MinLength(2)
     * @Assert\MaxLength(64)
     */
    private $lastname;

    static public function loadValidatorMetadata(\Symfony\Component\Validator\Mapping\ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('firstname', new Assert\NotNull());
        $metadata->addPropertyConstraint('firstname', new Assert\NotBlank(array(
            'message' => 'You must enter a first name',
        )));
        $metadata->addPropertyConstraint('firstname', new Assert\MinLength(array('limit' => 2, 'message' => 'A first name should have more than {{ limit }} characters in it.')));
        $metadata->addPropertyConstraint('firstname', new Assert\MaxLength(64));

        $metadata->addPropertyConstraint('lastname', new Assert\NotNull());
        $metadata->addPropertyConstraint('lastname', new Assert\NotBlank(array(
            'message' => 'You must enter a last name',
        )));
        $metadata->addPropertyConstraint('lastname', new Assert\MinLength(array('limit' => 2, 'message' => 'A first name should have more than {{ limit }} characters in it.')));
        $metadata->addPropertyConstraint('lastname', new Assert\MaxLength(64));
    }

Default values on '/' broken?

Hi, this code snipped does not seem to work, hence the default value on the '/' route cannot be set with value()

require_once __DIR__.'/silex.phar';

$app = new Silex\Application();

$app->get('/{pageName}', function ($pageName) {
    return "Hello $pageName";
})
->value('pageName', 'index');

$app->run();

The result is a plain "Hello".

I'm getting blank page

Hey, I'm trying to use framework but it just gives me blank page on my production servers.

Although, in local machine everything works as it should be.

Codes I'm using are at http://github.com/batuhanicoz/fbidfinder-com/

(All of the 3 (2 production, 1 local) servers are running 5.3.2+)

edit: silly me, it was caused by a typo.

Error when setting monolog.level

Can't find why this falls with error ( Fatal error: Class 'Logger' not found in 'blabla' ):

$app->register(new MonologExtension(), array(
    'monolog.class_path'    => __DIR__.'/vendor/monolog/src',
    'monolog.logfile'       => __DIR__.'/development.log',    
    'monolog.name'          => 'cars',
    'monolog.level'         => Logger::INFO
)); 

Without monolog.level it works pretty good.

ValidationExtension should register Symfony\Component\Validator namespace

Now it it registers Symfony\Component\Validation, but uses classes from Symfony\Component\Validator.

As it seems to me like an overkill to fork and send pull request because of 3-char change, here's a patch:

diff --git a/src/Silex/Extension/ValidationExtension.php b/src/Silex/Extension/ValidationExtension.php
index 276e5df..fb86d9b 100644
--- a/src/Silex/Extension/ValidationExtension.php
+++ b/src/Silex/Extension/ValidationExtension.php
@@ -39,7 +39,7 @@ class ValidationExtension implements ExtensionInterface
         });

         if (isset($app['validation.class_path'])) {
-            $app['autoloader']->registerNamespace('Symfony\\Component\\Validation', $app['validation.class_path']);
+            $app['autoloader']->registerNamespace('Symfony\\Component\\Validator', $app['validation.class_path']);
         }
     }
 }

Could it be that silex is a bit slow?

Hi I tried to do some simple actions with silex (e.g. crud) but I think it is a bit slow. I use the simple /hello/{name} example and it needs about 1 sec until I see the response in the browser (measured in firebug). I mean only for displaying the name, one second is a long time. It shouldn't take longer than 250ms for such a simple action. Is this normal? Or is my apache not configured well?

Guidance on Working with Bundles

I've closely picking through Igor's Silex extension to use the RestBundle. I'm trying the same with beberlei's SimpleThingsFormExtraBundle. My objective is to reuse a Recaptcha implementation.

So far, it seems as if I can / must (?) bypass the /DependencyInjection and other Config items and just instantiate the classes I need and pass them the required parameters. It seems very closely tied to how the bundle itself is written, almost like writing a Silex extension for 3rd party libraries. For example, I'm having a hard time dealing with classes which require a ContainerInterface to be passed to it and how/where to init the bundle.

The version of silex always display

I just using basic php silex and it always display the version of silex.

require_once __DIR__.'/../vendor/silex.phar';
$app = new Silex\Application();
$app->get('/', function(){
    return 'home!';
});
$app->run();

It display:

Silex version d9d397b 2011-04-17 15:06:02 +0200 home!

... It's the last version of the .phar.

Thanks.

Mounting Apps Raises Exception in UrlMatcher.php

Using the latest Silex phar, with APC turned off going to http://myapp.local/register, I get this exception:

<?php
Symfony\Component\Routing\Exception\ResourceNotFoundException: in phar:///srv/www/iplant.local/htdocs/Library/silex.phar/vendor/Symfony/Component/Routing/Matcher/UrlMatcher.php on line 33

when I mount anything below 'Registration':

<?php
//Main.php

/**
 * Mount sub-applications
 */
$registration = require __DIR__ . '/Registration.php';
$app->mount('/register', $registration);

$admin = require __DIR__ . '/Admin.php';
$app->mount('/admin', $admin);

Commenting out Admin.php or using LazyApplication produces no errors. However, I do not understand why Silex is looking for the /register route in Admin; I have confirmed that the Exception is indeed raised in Admin.php. There are no php errors or syntax errors in it.

Also, this does not occur when visiting the root route '/'

MyExtension - current route name needed

I currently work on a breadcrumb extension. The breadcrumbs depend on each other so I try to do this with a pimple container, or maybe app share() I don't know at the moment.

Is it possible to get the actual route name which I had bind after get()? I looked in the url generator for some help, is request_context useful? Iam not very experienced of how to usage the of symfony components.

I want my my extension to check which route is requested. The Route name is then my key for a pimple key which builds an array (containing labels and links). Twig will render them later as App -> Customers -> Add e.g

[docs] Wrong link in doc/extensions/http_cache.rst

In line 48 there is a link which is obviously incorrect: The extension also provide ESI <http://www.doctrine-project.org/docs/dbal/2.0/en/>_ support::

However, I did not know which one would be correct, so I created this issue instead of sending a pull request ;)

routing in reused applications

the routing in reused applications seemed strange, cause this example (in /app1 for example)

$app->get('/{param_1}/{param_2}', function ($param_1,$param_2) use ($app) {

will not catch url like hostname/app1
with defined default values like this

->value('param_1',0)
->assert('param_1','[0-9]+')
->value('param_2',0)
->assert('param_2','[0-9]+');

is it correct behaviour, or im doing something wrong?

in the main controller this example works fine.

Relaese notes for silex.phar file

Right now if I am using silex.phar I have no way to know if my phar file is current (other than download the file once again and compare).

Could you please introduce a page for silex.phar release notes? Or at least show last update date on silex-project.org website?

It would be very helpful.

Thanks in advance!

Class 'Twig_Loader_Chain' not found in phar

Ok so I'm currently running in Win7x64 using ZendServer (Apache2 + PHP532). The error I'm seeing is:

[02-Sep-2011 20:22:50] PHP Fatal error: Class 'Twig_Loader_Chain' not found in phar://C:/Dev/Zend/Apache2/htdocs/test/silex/vendor/silex.phar/src/Silex/Extension/TwigExtension.php on line 46

I have Silex up and running (phar).

My next step is Twig and there I am unstuck.

I downloaded and placed Twig into vendor\twig\ (so all the Twig PHP files are in vendor\twig\lib\Twig)

My register code looks like:

$app->register(new Silex\Extension\TwigExtension(), array(
  'twig.class_path' => __DIR__.'/vendor/twig/lib',
  'twig.path'       => __DIR__.'/views',
  'twig.options' => array(
    'cache' => __DIR__.'/cache',
  ),
));

So... I'm kinda stuck? From reading Silex docs Twig docs, it seems I'm doing everything correctly?

Any pointers appreciated.

Outdated phar archive

I wrote a Silex extension based on the current Silex code. Then, I downloaded the phar archive using the link on http://silex.sensiolabs.org/installation to create a small app using my code and it broke everything. The phar archive contains an old version of Silex (for instance without the charset flag and with the old TwigExtension).
Btw, the current master branch of Silex is not compatible anymore with the released versions of Twig (as the Twig_Loader_Chain class does not exist in 1.1), which is not mentioned anywhere in the doc.

So what is the correct way to write an extension now: using the version of Silex distributed on the website (in which case a tag should be created in the git repo to make it easy to know the Silex code without unpacking the phar) or the master branch ?
They are not compatible so I need to make a choice about the supported version.

Strange error when including phar file

Hi

I'm running into a very strange error when trying to include the silex.phar using

require_once __DIR__.'/silex.phar';

Which gives me

???

and hence subsequently

Fatal error: Class 'Silex\Application' not found...

All phar-related settings are set according to the docs

phar.readonly = Off
phar.require_hash = Off
suhosin.executor.include.whitelist = phar

Any ideas?

Symfony bridge twig issue

When try to render form with 'file' field appears error:

Catchable fatal error: Argument 1 passed to Symfony\Bridge\Twig\Extension\FormExtension::renderWidget() must be an instance of Symfony\Component\Form\FormView, null given, called in /var/www/silex/vendor/twig/lib/Twig/Environment.php(302) : eval()'d code on line 818 and defined in /var/www/silex/vendor/Symfony/Bridge/Twig/Extension/FormExtension.php on line 160 Call Stack: 0.0001 327708 1. {main}() /var/www/silex/index.php:0 0.0107 904296 2. Silex\Application->run() /var/www/silex/index.php:7 0.0144 1365008 3. Silex\Application->handle() phar:///var/www/silex/framework/silex.phar/src/Silex/Application.php:143 0.0153 1457396 4. Symfony\Component\HttpKernel\HttpKernel->handle() phar:///var/www/silex/framework/silex.phar/src/Silex/Application.php:147 0.0153 1457396 5. Symfony\Component\HttpKernel\HttpKernel->handleRaw() phar:///var/www/silex/framework/silex.phar/vendor/Symfony/Component/HttpKernel/HttpKernel.php:25 0.0685 4035572 6. call_user_func_array() phar:///var/www/silex/framework/silex.phar/vendor/Symfony/Component/HttpKernel/HttpKernel.php:47 0.0685 4035764 7. controllers\Admin->add() phar:///var/www/silex/framework/silex.phar/vendor/Symfony/Component/HttpKernel/HttpKernel.php:0 0.0895 5562120 8. Twig_Environment->render() /var/www/silex/controllers/Admin.php:28 0.0972 5611776 9. Twig_Template->render() /var/www/silex/vendor/twig/lib/Twig/Environment.php:282 0.0972 5653164 10. Twig_Template->display() /var/www/silex/vendor/twig/lib/Twig/Template.php:197 0.0972 5653328 11. __TwigTemplate_1fbc0929de0e54501a605e147932f589->doDisplay() /var/www/silex/vendor/twig/lib/Twig/Template.php:178 0.0973 5653964 12. Twig_Template->display() /var/www/silex/vendor/twig/lib/Twig/Environment.php(302) : eval()'d code:33 0.0973 5653964 13. __TwigTemplate_68c6401a6daaab27e8e7d479adf3c317->doDisplay() /var/www/silex/vendor/twig/lib/Twig/Template.php:178 0.0976 5656520 14. Twig_Template->displayBlock() /var/www/silex/vendor/twig/lib/Twig/Environment.php(302) : eval()'d code:67 0.0976 5656728 15. call_user_func() /var/www/silex/vendor/twig/lib/Twig/Template.php:95 0.0976 5656760 16. __TwigTemplate_1fbc0929de0e54501a605e147932f589->block_content() /var/www/silex/vendor/twig/lib/Twig/Template.php:0 0.3154 8313596 17. Symfony\Bridge\Twig\Extension\FormExtension->renderWidget() /var/www/silex/vendor/twig/lib/Twig/Environment.php(302) : eval()'d code:47 0.3154 8313836 18. Symfony\Bridge\Twig\Extension\FormExtension->render() /var/www/silex/vendor/Symfony/Bridge/Twig/Extension/FormExtension.php:162 0.3155 8319492 19. Twig_Template->renderBlock() /var/www/silex/vendor/Symfony/Bridge/Twig/Extension/FormExtension.php:242 0.3155 8360600 20. Twig_Template->displayBlock() /var/www/silex/vendor/twig/lib/Twig/Template.php:132 0.3155 8363108 21. call_user_func() /var/www/silex/vendor/twig/lib/Twig/Template.php:95 0.3155 8363140 22. __TwigTemplate_738c7cccee7a97b620bd2e05c41a3173->block_form_widget() /var/www/silex/vendor/twig/lib/Twig/Template.php:0 0.3156 8404328 23. Twig_Template->renderBlock() /var/www/silex/vendor/twig/lib/Twig/Environment.php(302) : eval()'d code:894 0.3156 8445436 24. Twig_Template->displayBlock() /var/www/silex/vendor/twig/lib/Twig/Template.php:132 0.3156 8447872 25. call_user_func() /var/www/silex/vendor/twig/lib/Twig/Template.php:95 0.3156 8447904 26. __TwigTemplate_738c7cccee7a97b620bd2e05c41a3173->block_field_rows() /var/www/silex/vendor/twig/lib/Twig/Template.php:0 0.3182 8555044 27. Symfony\Bridge\Twig\Extension\FormExtension->renderRow() /var/www/silex/vendor/twig/lib/Twig/Environment.php(302) : eval()'d code:220 0.3182 8555280 28. Symfony\Bridge\Twig\Extension\FormExtension->render() /var/www/silex/vendor/Symfony/Bridge/Twig/Extension/FormExtension.php:126 0.3183 8561244 29. Twig_Template->renderBlock() /var/www/silex/vendor/Symfony/Bridge/Twig/Extension/FormExtension.php:242 0.3183 8602352 30. Twig_Template->displayBlock() /var/www/silex/vendor/twig/lib/Twig/Template.php:132 0.3183 8604860 31. call_user_func() /var/www/silex/vendor/twig/lib/Twig/Template.php:95 0.3183 8604892 32. __TwigTemplate_738c7cccee7a97b620bd2e05c41a3173->block_field_row() /var/www/silex/vendor/twig/lib/Twig/Template.php:0 0.3186 8644668 33. Symfony\Bridge\Twig\Extension\FormExtension->renderWidget() /var/www/silex/vendor/twig/lib/Twig/Environment.php(302) : eval()'d code:876 0.3186 8644908 34. Symfony\Bridge\Twig\Extension\FormExtension->render() /var/www/silex/vendor/Symfony/Bridge/Twig/Extension/FormExtension.php:162 0.3186 8650696 35. Twig_Template->renderBlock() /var/www/silex/vendor/Symfony/Bridge/Twig/Extension/FormExtension.php:242 0.3187 8691804 36. Twig_Template->displayBlock() /var/www/silex/vendor/twig/lib/Twig/Template.php:132 0.3187 8694312 37. call_user_func() /var/www/silex/vendor/twig/lib/Twig/Template.php:95 0.3187 8694344 38. __TwigTemplate_738c7cccee7a97b620bd2e05c41a3173->block_file_widget() /var/www/silex/vendor/twig/lib/Twig/Template.php:0 0.3188 8735496 39. Symfony\Bridge\Twig\Extension\FormExtension->renderWidget() /var/www/silex/vendor/twig/lib/Twig/Environment.php(302) : eval()'d code:818

SessionExtension cannot handle multiple apps

If you have two or more apps (via $app->mount()) that use the SessionExtension, things break, with only the first app (that rule may not be exact) being able to save it's session data.

e.g.
$a = new Silex\Application();
$a->register(new Silex\Extension\SessionExtension());
$b = new Silex\Application();
$b->register(new Silex\Extension\SessionExtension());
$b->get('/', function() use ($b) { echo $b['session']->get('test', 'no'); $b['session']->set('test', 'yes'); return ' - always no'; });
$a->mount('test', $b);

Then go to index.php/b/ and no matter how many times you refresh, it always echos no.

Simple internal cache system

I haven't found internal cache system in Silex.
So I think it would be great to have simple cache system inside the framework.
Look at this example to see what do i mean:

require_once __DIR__.'/silex.phar'; 

$app = new Silex\Application(); 

$app->get('/static_page', function() { 
    return "Static page content"; 
})->cache(60);  // this creates local copy of page for 60 seconds 
                           //and returns the copy instead of  generating page each time

$app->run(); 

What do you think about this?

[docs] WebTestCase and extensions

Following things still need documenting:

  • WebTestCase ✔
  • DoctrineExtension ✔ (no tests yet)
  • FormExtension
  • SwiftmailerExtension ✔ (no tests yet)
  • SymfonyBridgesExtension ✔ (no tests yet)
  • TranslationExtension ✔ (no tests yet)
  • ValidationExtension ✔
  • Controller (value, assert) ✔

WebTestCase doc's sample code not correct

Hi.
I found WebTestCase documentaion sample code not correct,
Doc says "For your WebTestCase, you will have to implement a createApplication method, which returns your application. ",
but PHP require statement return only boolean.

IMHO, it should be like this.

public function createApplication()
{
     require __DIR__.'/path/to/app.php';
     return $app;
}

Regards,

Redirect in before method

Hi!

Is possible use the redirect method in before method? I used the next code idea for protect my routes, but can not get the redirect to work correctly.

$app->before(function() use ($app) {
    if ($app['request']->get('require_authentication')) {   
        if (null === $user = $app['session']->get('user')) {
            return $app->redirect('/login');
                }
    }
});

$app->get('/protected', function ($name) {
    return "Protected route";
})->value('require_authentication', true);

Document how to use Silex without the phar

Right now, the documentation only documents how to use Silex with the phar. It's really convenient, but we should also document how to use Silex without it for several reasons: first, using a phar comes with a lot of problems, then, it's now that complex to bypass the phar and have more flexibility about how you manage your dependencies and their upgrades.

Error : Class ContainerAware not found...

Hi,
I'm pretty new ( a big noob ) to silex and symfony, so maybe my question doesn't make
any sense.

For a project oriented performance, i've tried to implementing the
"RedisBundle" symfony2 package from https://github.com/snc/RedisBundle

In the bootstrap.php i've put something like that :

use Silex\Application;
use Snc\RedisBundle\RedisBundle;
$app = new Application();
// Register SNC + PREDIS classes for autoloading
$app['autoloader']->registerNamespaces(array(
'Snc' => DIR,
'Predis' => DIR.'/../vendor/predis/lib'
));

// Just to test...
$app->register(new RedisBundle());

The RedisBundle class was loaded. moreover this class using the namespace "Symfony\Component\HttpKernel
\Bundle\Bundle".

However i've catched this fatal :

Fatal error: Class 'Symfony\Component\DependencyInjection
\ContainerAware' not found in phar:/// PATH/silex/vendor/silex.phar/
vendor/Symfony/Component/HttpKernel/Bundle/Bundle.php on line 8

When i tried also in the bootstrap.php a thing like that :

use Symfony\Component\DependencyInjection\ContainerBuilder;
$container = new ContainerBuilder();

that throw an exception ;

Fatal error: Class 'Symfony\Component\DependencyInjection
\ContainerBuilder' not found in /home/kroknet/00_sources/silex/src/
bootstrap.php on line 19

I'm totally lost :-(

please help :-)

Regards

Merging the Doctrine Extensions

It has been suggested that we get the Doctrine Extensions merged up, and consolidate all that code into one nice extension.

Currently we have these (let me know if I missed any):

  1. DoctrineExtension (bundled in Silex now)
  2. https://github.com/flintstones/DoctrineOrm
  3. https://github.com/awildeep/Silex-DoctrineMultiDbExtension
  4. https://github.com/docteurklein/SilexExtensions - DoctrineOrm

I would love to see the syntax support the bundled extensions syntax, but in addition support the features these other extensions provide. As for features that need to be supported to reduce the number of extensions:

  1. ORM
    • Thought: make this an extension by itself. If you want ORM, install it, otherwise just use the standard Doctrine extension
  2. Multiple DB support
  3. ... Did I miss anything?

I'll keep this top note as up-to-date as I can.

Routing does not handle trailing slashes consistently

This may be merely something to add to the docs.

Using a simple application such as the following:

<?php

require_once __DIR__.'/../silex.phar';
use Symfony\Component\HttpFoundation\Response;

$app = new Silex\Application();

$app->get('/', function () use ($app) {
      return new Response('Home root');
});
$app->get('/hello', function () use ($app) {
      return new Response('No trailing slash');
});
$app->get('/hello/', function () use ($app) {
      return new Response('With trailing slash');
});

$app->run();

this is the observed behavior:

However expected behaviour would be that the last route is inaccessible:

If the last route is not defined, the result of requesting /hello/ is "Sorry, the page you are looking for could not be found." - but you'd expect it to match the routefor /hello.

This is testing on an arch linux machine running nginx - though that shouldn't really be much of a factor.

fatal error in debian squeeze

I'm on debian with standard packages:

  1. php 5.3.3
  2. apache 2.2.16
  3. silex.phar (latest version)

I'm trying to run the helloworld:

<?php
require_once __DIR__.'/silex.phar'; 
$app = new Silex\Application(); 
$app->get('/hello/{name}', function($name) { 
    return "Hello $name"; 
}); 
$app->run();

Here is the error I got:

PHP Fatal error:  Uncaught exception 'Symfony\Component\Routing\Exception\ResourceNotFoundException' in phar://var/www/silex.phar/vendor/Symfony/Component/Routing/Matcher/UrlMatcher.php:33
Stack trace:
#0 phar://var/www/silex.phar/vendor/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php(10): Symfony\Component\Routing\Matcher\UrlMatcher->match('/')
#1 phar://var/www/silex.phar/src/Silex/Application.php(163): Symfony\Component\Routing\Matcher\RedirectableUrlMatcher->match('/')
#2 [internal function]: Silex\Application->onKernelRequest(Object(Symfony\Component\HttpKernel\Event\GetResponseEvent))
#3 phar://var/www/silex.phar/vendor/Symfony/Component/EventDispatcher/EventDispatcher.php(74): call_user_func(Array, Object(Symfony\Component\HttpKernel\Event\GetResponseEvent))
#4 phar://var/www/silex.phar/vendor/Symfony/Component/EventDispatcher/EventDispatcher.php(15): Symfony\Component\EventDispatcher\EventDispatcher->doDispatch(Array, 'kernel.request', Object(Symfony\Component\HttpKernel\Event\GetResponseEvent))
#5 ph in phar://var/www/silex.phar/src/Silex/Application.php on line 169

Any help is welcomed :)

[Bug] Update CLI command not working properly when script is called from other directory

The following code is used in silex.phar to handle update command:

        $remoteFilename = 'http://silex-project.org/get/silex.phar';
        $localFilename = getcwd().'/silex.phar';

        file_put_contents($localFilename, file_get_contents($remoteFilename));

When calling:

      php src/Silex/silex.phar update

Silex will save silex.phar file in current directory . (and NOT ./src/Silex/ as it is supposed to be).

The solution is to use __DIR__ instead of getcwd(). See more here: http://www.php.net/manual/en/function.getcwd.php#87087

HEAD http method?

I've noticed in my log files that some requests are using the HEAD method on my app. This throws up an Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException, and I don't know of a way to handle this.

Is there a workaround? Or is this something that would need to be looked at?

problem with *Reusing applications*

i've got the problem with mounting parts of application. folowing the chapter Reusing applications (http://silex-project.org/doc/usage.html) i always got an infinity loop of redirect, then my app is down. got the same problems on simple require and with Silex\LazyApplication too. think that i do something wrong or this component is broken,

The parts of my app using the same database & template engine objects. Should i create them in the main app & module for mounting? For example i got a main controller (index page, some news page or etc) and when i get request like "/blog" i want to attach blog app and look for correct controller method there. How can i do this? If someone got a working example please post it here. Now i just include modules into main "controller" (without starting & returning $app, just methods for in same context like main "controller").

Bad order with parameters at method Application->onCoreRequest

Hi,

I've been playing with Silex a little, and just discovered, that the methon onCoreRequest creates a new RequestContext, but it creates it wrong... The code is like:

// line 312 of Silex/Application.php
public function onCoreRequest(KernelEvent $event)
{
    $this['request'] = $event->getRequest();
    $this['request_context'] = new RequestContext(
        $this['request']->getBaseUrl(),
        $this['request']->getMethod(),
        $this['request']->getHost(),
        $this['request']->getPort(),
        $this['request']->getScheme()
    );

The signature of RequestContext constructor is: baseUrl, Method, Host, Schema, Port, HTTPSPort, so the code should be:

// line 312 of Silex/Application.php
public function onCoreRequest(KernelEvent $event)
{
    $this['request'] = $event->getRequest();
    $this['request_context'] = new RequestContext(
        $this['request']->getBaseUrl(),
        $this['request']->getMethod(),
        $this['request']->getHost(),
        $this['request']->getScheme(),
        $this['request']->getPort()
    );

Notice the swap between the last two parameters.

I've not attached a pull request because it's very simply to change :-D

Fatal error: Class 'Locale' not found using sessions

I'm running the following code on php 5.3.1 on MacOS

<?php
require_once 'phar://'.__DIR__.'/silex.phar/autoload.php'; 
// require_once __DIR__.'/silex.phar' doesn't work for me
$app = new Silex\Application();

$app->register(new Silex\Extension\SessionExtension()); 


$app
    ->get('/', function () {
        return "Silex project";
    })
    ->bind('homepage');

$app->run();
?>

When I execute this code I obtain thi fatal error:

Fatal error: Class 'Locale' not found in phar:///...
/silex.phar/vendor/Symfony/Component/HttpFoundation/Session.php on line 188

Isn't session component a silex built-in? How can I solve?
Thank you

Best practice to register Twig extensions from an extension

What is the best practice to register a Twig extension from a Silex extension ? I see 2 solutions with the current code:

Using twig.configure

I could overwrite twig.configure (as it is a place meant to do such things) but using it in extensions means that every people using it would have to write it in a way avoiding to delete previous changes:

<?php
// in the extension register method

$oldconfigure = isset($app['twig.configure']) ? $app['twig.configure']: function(){};
$app['twig.configure'] = $app->protect(function($twig) use ($oldConfigure, $app) {
    $oldConfigure($twig);
    $twig->addExtension($app['my_extension'])
});

And note that the TwigExtension would need to be changed too to avoid overwriting it if it already exists (so that extensions modifying it can be registered before the TwigExtension too).
The drawback is that every user would have to use this way, including the end-user (thus making it less user-friendly)

Overwritting the definition

I could also do it by changing the definition of the Twig environment:

<?php
// in the extension register method

if (isset($app['twig'])) {
    $oldTwig = $app->raw('twig');
    $app['twig'] = $app->share(function($c) use ($oldTwig) {
        $twig = $oldTwig($c);
        $twig->addExtension($c['my_extension']);

        return $twig;
    });
}

Advantage: The end-user can use twig.configure in the simple way, without having to take care to keep previous changes.

Drawback: The extension must now be registered after the Twig extension otherwise the Twig integration is ignored. This could potentially lead to a circular dependency for the registration order (which would not work) but it is likely to be an edge case

Improving the current code to create a clean way to do it

The idea here would be to have a way to let the TwigExtension know that some services should be registered in the environment (what is achieved using tags in Symfony2). But this may be overkill for Pimple.

What do you think about it ?

Inject Application into before/after filters, controllers.

It's a pity that PHP has explicit closures, and so it happens quite often that you forget to use() the application.

For convenience it may be a good idea to inject it into before/after filters (as first argument?). And also into the controller closures. Perhaps we could just set a parameter for 'app', so that $app becomes the application.

$app->before(function ($app) {
    ...
});

$app->get('/{page}', function ($app, $page) {
    ...
});

An (imo too verbose) alternative would be using type hinting, so:

$app->get('/{page}', function (Silex\Application $foo, $page) {
    $foo is now $app...
});

Thoughts?

Trying to combine Silex with Twig & Translations extensions.

Hi, I'm wondering if there's a simple way to access translations directly from Twig templates in a Silex project. I don't want to give parameters to my templates for each single sentence I want to translate.

Is it possible to access something like {{app.trans.my_translation_key}} directly in templates?

unable to register extension validator

Hi everybody

in the bootstrap.php file, i've tried to register the validator extension with something like this :

$app->register(new Silex\Extension\ValidatorExtension(), array(
'validator.class_path' => VENDOR.'/Symfony/Component/Validator'
));

i've got well defined VENDOR constant and made a git clone of the symfony2 component validator.
However i catched a fatal error when i tried to access to the validator service in the app with something like this :

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints;
...
...
$obj = $app['myNewService']
->setName($app['request']->get('name'))
->setPrename($app['request']->get('prename'))
->setEmail($app['request']->get('email'))
->setParams(sha1(time()));

$violations = $app['validator']->validate($post);

The fatal is :

Fatal error: Class 'Symfony\Component\Validator\Validator' not found in phar:///home/kroknet/00_sources/silex/vendor/silex.phar/src/Silex/Extension/ValidatorExtension.php on line 14

Any advices ?

( no troubles to get working twig, register my own service, and predis extension working well also... ) I followed the tutorial from the official SILEX website

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.