I work on CentOS.
I’ve followed the tutorials :
-
http://symfony.com/doc/current/best_practices/creating-the-project.html
-
https://symfony.com/doc/current/page_creation.html
As I use Apache, I’ve followed this page too :
- https://symfony.com/doc/current/setup/web_server_configuration.html
I made a default controller and a default template. With this controller (/) I get the the following error (within the debug toolbar):
An error occurred while loading the web debug toolbar. Open the web profiler.
When I click on the link : «Open the web profiler», I can see the Apache response :
Not Found
The requested URL /_profiler/177403 was not found on this server.
In the chrome inspector, I can see :
GET http://172.31.18.7/_wdt/177403 404 (Not Found)
Here’s the interesting part of my composer.json :
"require": {
"php": "^7.1.3",
"ext-iconv": "*",
"doctrine/doctrine-fixtures-bundle": "^3.0",
"sensio/framework-extra-bundle": "^5.1",
"sonata-project/admin-bundle": "^3.35",
"sonata-project/doctrine-orm-admin-bundle": "^3.6",
"symfony/apache-pack": "^1.0",
"symfony/console": "^4.0",
"symfony/flex": "^1.0",
"symfony/framework-bundle": "^4.0",
"symfony/lts": "^4@dev",
"symfony/maker-bundle": "^1.4",
"symfony/orm-pack": "^1.0",
"symfony/requirements-checker": "^1.1",
"symfony/security-bundle": "^4.0",
"symfony/twig-bundle": "^4.0",
"symfony/validator": "^4.0",
"symfony/yaml": "^4.0"
},
"require-dev": {
"sensiolabs/security-checker": "^4.1",
"symfony/dotenv": "^4.0",
"symfony/web-profiler-bundle": "^4.0"
},
my httpd.conf :
<VirtualHost *:80>
DocumentRoot /var/www/html/elora/public
ServerName eloradev
ServerAlias www.elora.dev
DirectoryIndex index.php
<Directory "elora/public">
AllowOverride all
Order Allow,Deny
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
</Directory>
<Directory elora>
Options FollowSymlinks
</Directory>
ErrorLog /var/apache/logs/error.log
CustomLog /var/apache/logs/access.log combined
</VirtualHost>
And my .htaccess :
DirectoryIndex index.php
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteCond %{HTTP:Authorization} .
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^index.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
RewriteRule ^ %{ENV:BASE}/index.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
<IfModule mod_alias.c>
RedirectMatch 307 ^/$ /index.php/
</IfModule>
</IfModule>
And, to finish, my /lucky/number (https://symfony.com/doc/current/page_creation.html) raises the apache message :
Not Found
The requested URL /lucky/number was not found on this server.
It looks like the routing component does’nt work.
The router rules (debug:router) :
-------------------------- -------- -------- ------ -------------------
Name Method Scheme Host Path
-------------------------- -------- -------- ------ -----------------------
app_homepage ANY ANY ANY /
app_lucky ANY ANY ANY /lucky
app_lucky_number ANY ANY ANY /lucky/number
_twig_error_test ANY ANY ANY /_error/{code}.{_format}
_wdt ANY ANY ANY /_wdt/{token}
_profiler_home ANY ANY ANY /_profiler/
_profiler_search ANY ANY ANY /_profiler/search
_profiler_search_bar ANY ANY ANY /_profiler/search_bar
_profiler_phpinfo ANY ANY ANY /_profiler/phpinfo
_profiler_search_results ANY ANY ANY /_profiler/{token}/search/results
_profiler_open_file ANY ANY ANY /_profiler/open
_profiler ANY ANY ANY /_profiler/{token}
_profiler_router ANY ANY ANY /_profiler/{token}/router
_profiler_exception ANY ANY ANY /_profiler/{token}/exception
_profiler_exception_css ANY ANY ANY /_profiler/{token}/exception.css
-------------------------- -------- -------- ------ -----------------------
I’ve manually created the directory /_wdt, in case, but it did’nt change anything.
I’ve checked errors with debug:event-dispatcher, nothing special.
I’ve noticed that the cache for the profiler is in that directory : var/cache/dev/profiler/03/74/ and is named 177403
One more thing, I’ve ran composer with the ‘root’ user. And I’ve used chown to change the owner of my project.
Here’s a part of my file .env :
###> symfony/framework-bundle ###
APP_ENV=dev
Symfony version(s) affected: 5.0.0
Description
I’m working with Symfony 5.X, it’s a fresh install on docker with the image «bitnami/symfony». I use too «bitnami/nginx» and «bitnami/php-fpm». All work good except the web profiler toolbar.
I passed the 2 last days on Google searching for a solution but nothing work. I can access the url /_profiler/ but if I click on a token to view some details I get an error 500.
TypeError:
Argument 5 passed to SymfonyComponentErrorHandlerErrorRendererHtmlErrorRenderer::__construct() must be a string or a callable, SymfonyComponentHttpFoundationRequestStack given.
at /app/simtp/vendor/symfony/error-handler/ErrorRenderer/HtmlErrorRenderer.php:53
at SymfonyComponentErrorHandlerErrorRendererHtmlErrorRenderer->__construct(true, 'UTF-8', object(FileLinkFormatter), '/app/simtp', object(RequestStack), object(Logger))
(/app/simtp/var/cache/dev/ContainerIRQxaSE/App_KernelDevDebugContainer.php:2035)
at ContainerIRQxaSEApp_KernelDevDebugContainer->getErrorHandler_ErrorRenderer_HtmlService()
(/app/simtp/var/cache/dev/ContainerIRQxaSE/App_KernelDevDebugContainer.php:719)
at ContainerIRQxaSEApp_KernelDevDebugContainer->getErrorControllerService()
(/app/simtp/vendor/symfony/dependency-injection/Container.php:242)
at SymfonyComponentDependencyInjectionContainer->make('error_controller', 1)
(/app/simtp/vendor/symfony/dependency-injection/Container.php:222)
at SymfonyComponentDependencyInjectionContainer->get('error_controller')
(/app/simtp/vendor/symfony/http-kernel/Controller/ContainerControllerResolver.php:53)
at SymfonyComponentHttpKernelControllerContainerControllerResolver->instantiateController('error_controller')
(/app/simtp/vendor/symfony/framework-bundle/Controller/ControllerResolver.php:29)
at SymfonyBundleFrameworkBundleControllerControllerResolver->instantiateController('error_controller')
(/app/simtp/vendor/symfony/http-kernel/Controller/ControllerResolver.php:108)
at SymfonyComponentHttpKernelControllerControllerResolver->createController('error_controller')
(/app/simtp/vendor/symfony/http-kernel/Controller/ContainerControllerResolver.php:42)
at SymfonyComponentHttpKernelControllerContainerControllerResolver->createController('error_controller')
(/app/simtp/vendor/symfony/http-kernel/Controller/ControllerResolver.php:86)
at SymfonyComponentHttpKernelControllerControllerResolver->getController(object(Request))
(/app/simtp/vendor/symfony/http-kernel/Controller/TraceableControllerResolver.php:38)
at SymfonyComponentHttpKernelControllerTraceableControllerResolver->getController(object(Request))
(/app/simtp/vendor/symfony/http-kernel/HttpKernel.php:128)
at SymfonyComponentHttpKernelHttpKernel->handleRaw(object(Request), 2)
(/app/simtp/vendor/symfony/http-kernel/HttpKernel.php:67)
at SymfonyComponentHttpKernelHttpKernel->handle(object(Request), 2, false)
(/app/simtp/vendor/symfony/http-kernel/EventListener/ErrorListener.php:60)
at SymfonyComponentHttpKernelEventListenerErrorListener->onKernelException(object(ExceptionEvent), 'kernel.exception', object(TraceableEventDispatcher))
(/app/simtp/vendor/symfony/event-dispatcher/Debug/WrappedListener.php:117)
at SymfonyComponentEventDispatcherDebugWrappedListener->__invoke(object(ExceptionEvent), 'kernel.exception', object(TraceableEventDispatcher))
(/app/simtp/vendor/symfony/event-dispatcher/EventDispatcher.php:230)
at SymfonyComponentEventDispatcherEventDispatcher->callListeners(array(object(WrappedListener), object(WrappedListener), object(WrappedListener), object(WrappedListener)), 'kernel.exception', object(ExceptionEvent))
(/app/simtp/vendor/symfony/event-dispatcher/EventDispatcher.php:59)
at SymfonyComponentEventDispatcherEventDispatcher->dispatch(object(ExceptionEvent), 'kernel.exception')
(/app/simtp/vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php:151)
at SymfonyComponentEventDispatcherDebugTraceableEventDispatcher->dispatch(object(ExceptionEvent), 'kernel.exception')
(/app/simtp/vendor/symfony/http-kernel/HttpKernel.php:206)
at SymfonyComponentHttpKernelHttpKernel->handleThrowable(object(TypeError), object(Request), 1)
(/app/simtp/vendor/symfony/http-kernel/HttpKernel.php:99)
at SymfonyComponentHttpKernelHttpKernel->terminateWithException(object(TypeError), object(Request))
(/app/simtp/vendor/symfony/http-kernel/EventListener/DebugHandlersListener.php:114)
at SymfonyComponentHttpKernelEventListenerDebugHandlersListener::SymfonyComponentHttpKernelEventListener{closure}(object(TypeError))
(/app/simtp/vendor/symfony/error-handler/ErrorHandler.php:592)
at SymfonyComponentErrorHandlerErrorHandler->handleException(object(TypeError))
I think it’s for this reason that my toolbar is showing «An error occurred while loading the web debug toolbar».
Here is my Nginx conf for this site:
server {
server_name simtp.local www.simtp.local;
root /app/simtp/public;
listen 0.0.0.0:8080;
location / {
# try to serve file directly, fallback to index.php
try_files $uri /index.php$is_args$args;
#try_files $uri $uri/ /index.php?q=$uri&$args;
}
# optionally disable falling back to PHP script for the asset directories;
# nginx will return a 404 error when files are not found instead of passing the
# request to Symfony (improves performance but Symfony's 404 page is not displayed)
# location /bundles {
# try_files $uri =404;
# }
location ~ ^/index.php(/|$) {
fastcgi_pass phpfpm:9000;
fastcgi_split_path_info ^(.+.php)(/.*)$;
include fastcgi_params;
# optionally set the value of the environment variables used in the application
# fastcgi_param APP_ENV prod;
# fastcgi_param APP_SECRET <app-secret-id>;
# fastcgi_param DATABASE_URL "mysql://db_user:db_pass@host:3306/db_name";
# When you are using symlinks to link the document root to the
# current version of your application, you should pass the real
# application path instead of the path to the symlink to PHP
# FPM.
# Otherwise, PHP's OPcache may not properly detect changes to
# your PHP files (see https://github.com/zendtech/ZendOptimizerPlus/issues/126
# for more information).
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $document_root;
# Prevents URIs that include the front controller. This will 404:
# http://domain.tld/index.php/some-path
# Remove the internal directive to allow URIs like this
internal;
}
# return 404 for all other php files not matching the front controller
# this prevents access to other php files you don't want to be accessible.
location ~ .php$ {
return 404;
}
#error_log /opt/bitnami/nginx/project_error.log;
#access_log /opt/bitnami/nginx/project_access.log;
}
My docker-compose file:
version: '2'
services:
nginx:
image: 'bitnami/nginx:1.16'
ports:
- '8784:8080'
networks:
- default
depends_on:
- phpfpm
volumes:
- './simtp/public/simtp.conf:/opt/bitnami/nginx/conf/server_blocks/simtp.conf:ro'
phpfpm:
image: 'bitnami/php-fpm:latest'
networks:
- default
volumes:
- './simtp:/app/simtp'
simtp:
image: 'bitnami/symfony:1'
ports:
- '8780:8000'
volumes:
- '.:/app'
environment:
- TZ=America/New_York
- SYMFONY_PROJECT_NAME=simtp
depends_on:
- simtp_api
- nginx
networks:
- default
simtp_api:
image: 'bitnami/symfony:1'
ports:
- '8782:8000'
volumes:
- '.:/app'
environment:
- TZ=America/New_York
- SYMFONY_PROJECT_NAME=simtp_api
- MYSQL_ROOT_USER=root
- MYSQL_ROOT_PASSWORD=
- MYSQL_USER=simtp01
- MYSQL_PASSWORD=***************
- MYSQL_DATABASE=simtp
- ALLOW_EMPTY_PASSWORD=yes
depends_on:
- mysqldb
- nginx
networks:
default:
aliases:
- api.simtp.local
mysqldb:
...
...
...
I read on forums that some people fix this problem with the package symfony/apache-pack but I don’t want to use Apache because I have already Nginx.
I have no more idea, I have tried so much things, if someone can help me it will be nice.
How to reproduce
- Install Symfony & web profiler —dev
- Make:Controller
- Go to /_profiler
- Click on a token
- Boom, error 500
Additional context :
Nginx log:
nginx_1 | 172.18.0.1 — — [03/Dec/2019:02:52:24 +0000] «GET /_profiler/79f958 HTTP/1.1» 500 196482 «http://simtp.local:8784/_profiler/empty/search/results?limit=10» «Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0»
Содержание
- Symfony 5.x — An error occurred while loading the web debug toolbar #34770
- Comments
- An error occurred while loading the web debug toolbar. #28847
- Comments
- Troubleshooting Problems
- Discovering the Symfony Debugging Tools
- Understanding Symfony Environments
- Managing Environment Configurations
- Configuring your IDE
- Debugging Production
- Web Debug Toolbar & the Profiler!
- Video not working?
- Hello Web Debug Toolbar!
- Hello Profiler: The Toolbar’s Powerful Sidekick
- Magic with The dump() Function
Symfony 5.x — An error occurred while loading the web debug toolbar #34770
Symfony version(s) affected: 5.0.0
Description
I’m working with Symfony 5.X, it’s a fresh install on docker with the image «bitnami/symfony». I use too «bitnami/nginx» and «bitnami/php-fpm». All work good except the web profiler toolbar.
I passed the 2 last days on Google searching for a solution but nothing work. I can access the url /_profiler/ but if I click on a token to view some details I get an error 500.
I think it’s for this reason that my toolbar is showing «An error occurred while loading the web debug toolbar».
Here is my Nginx conf for this site:
My docker-compose file:
I read on forums that some people fix this problem with the package symfony/apache-pack but I don’t want to use Apache because I have already Nginx.
I have no more idea, I have tried so much things, if someone can help me it will be nice.
How to reproduce
- Install Symfony & web profiler —dev
- Make:Controller
- Go to /_profiler
- Click on a token
- Boom, error 500
Additional context :
Nginx log:
nginx_1 | 172.18.0.1 — — [03/Dec/2019:02:52:24 +0000] «GET /_profiler/79f958 HTTP/1.1» 500 196482 «http://simtp.local:8784/_profiler/empty/search/results?limit=10» «Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0»
The text was updated successfully, but these errors were encountered:
Источник
An error occurred while loading the web debug toolbar. #28847
Symfony version(s) affected: 4.1.6
Description
I redirect the user with an an event listener when he want to access to «login» or «register» if he is already logged, that works but then the web debug toolbar display only : «An error occurred while loading the web debug toolbar.»
How to reproduce
Use $this->authChecker->isGranted(‘IS_AUTHENTICATED_REMEMBERED’) in an event listener like i tryed first with my KernelRequestListener and then with RememberedSubscriber instead.
Possible Solution
Not found yet, i guess it’s about the token but after hours in the documentation i still don’t get it.
Additional context
I’m using FOSUser dev-master.
The text was updated successfully, but these errors were encountered:
Can you please create a small example application that allows to reproduce your issue?
At this point my app is not «big», i started with symfony/website-skeleton and friendsofsymfony/user-bundle, except some configuration, the event subscriber and my own css file : nothing more.
If your really prefere debbug it with a smaller version, so i could restart this by starting with symfony/skeleton wich will be a good exercice for me and allow us to isolate the bug probably. Otherwise you can clone it.
Thanks, your example application helps to reproduce. Looking at the application logs an internal error is triggered by your RememberedSubscriber when the FirewallListener is not triggered.
I think you need to inject the token storage into your event subscriber and exit early in case there is no token.
I am closing here as there is nothing we can do in Symfony about that.
I’ll try it and will confirm the success or report any problems if it is helpful.
Maybe the «issue» still going on. or i need probably to learn more about the token.
My code works well now with :
Are both displaying in the toolbar : «An error occurred while loading the web debug toolbar.»
@xabbuh do you confirm that’s not an issue from Symfony ? I tryed to get some informations about the token in the doc but it still blur for me.
Yes, when no route is found for a path the RouterListener quits with an exception. Then, the FirewallListener will not be called. This means that no token will be populated in the token storage. That’s why calling getRoles() in your first example does not work. Also, the authorization checker (which is used under the hood in your second example) cannot work without a token. So that usage will fail too.
Thank you for the time you have already spend here @xabbuh
But for what i see in the profiler and also in dev.log there is no exception, just a matched route before the redirect. Well i’ll look closer and thanks for the last explanation about the FirewallListener.
I know this is an old post, but I have the same issue and do not belive if ($this->security->getUser() !== null) < // . is the correct fix.
I dont know if it’s a bug, but it certaintly is weird. Why would the main page do everything as without a problem, but only the symfony toolbar not? No functionality is broken, except from the toolbar.
I get the error when using the event listener kernel.controller . I have not tested on other kernel.someEvent . It occurs when using/checking the current logged in user. I guess it is not yet logged in for the toolbar. But is for the main page. dump() also gives the user object.
When looking into the network tab in chrome dev tools, I get the following error message: «The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.»
And 3 times an AuthenticationCredentialsNotFoundException . The toolbar says: «An error occurred while loading the web debug toolbar.».
I guess the «Right» fix would be to login the user before hand. But again it seems to already be logged in (when dumping or looking at main page etc.). Just not for the toolbar.
Источник
Troubleshooting Problems
Setting up a project is also about having the right tools to debug problems. Fortunately, many nice helpers are already included as part of the webapp package.
To begin with, the Symfony Profiler is a time saver when you need to find the root cause of a problem.
If you have a look at the homepage, you should see a toolbar at the bottom of the screen:
The first thing you might notice is the 404 in red. Remember that this page is a placeholder as we have not defined a homepage yet. Even if the default page that welcomes you is beautiful, it is still an error page. So the correct HTTP status code is 404, not 200. Thanks to the web debug toolbar, you have the information right away.
If you click on the small exclamation point, you get the «real» exception message as part of the logs in the Symfony profiler. If you want to see the stack trace, click on the «Exception» link on the left menu.
Whenever there is an issue with your code, you will see an exception page like the following that gives you everything you need to understand the issue and where it comes from:
Take some time to explore the information inside the Symfony profiler by clicking around.
Logs are also quite useful in debugging sessions. Symfony has a convenient command to tail all the logs (from the web server, PHP, and your application):
Let’s do a small experiment. Open public/index.php and break the PHP code there (add foobar in the middle of the code for instance). Refresh the page in the browser and observe the log stream:
The output is beautifully colored to get your attention on errors.
Understanding Symfony Environments
As the Symfony Profiler is only useful during development, we want to avoid it being installed in production. By default, Symfony automatically installed it only for the dev and test environments.
Symfony supports the notion of environments. By default, it has built-in support for three, but you can add as many as you like: dev , prod , and test . All environments share the same code, but they represent different configurations.
For instance, all debugging tools are enabled in the dev environment. In the prod one, the application is optimized for performance.
Switching from one environment to another can be done by changing the APP_ENV environment variable.
When you deployed to Platform.sh, the environment (stored in APP_ENV ) was automatically switched to prod .
Managing Environment Configurations
APP_ENV can be set by using «real» environment variables in your terminal:
Using real environment variables is the preferred way to set values like APP_ENV on production servers. But on development machines, having to define many environment variables can be cumbersome. Instead, define them in a .env file.
A sensible .env file was generated automatically for you when the project was created:
Any package can add more environment variables to this file thanks to their recipe used by Symfony Flex.
The .env file is committed to the repository and describes the default values from production. You can override these values by creating a .env.local file. This file should not be committed and that’s why the .gitignore file is already ignoring it.
Never store secret or sensitive values in these files. We will see how to manage secrets in another step.
Configuring your IDE
In the development environment, when an exception is thrown, Symfony displays a page with the exception message and its stack trace. When displaying a file path, it adds a link that opens the file at the right line in your favorite IDE. To benefit from this feature, you need to configure your IDE. Symfony supports many IDEs out of the box; I’m using Visual Studio Code for this project:
Linked files are not limited to exceptions. For instance, the controller in the web debug toolbar becomes clickable after configuring the IDE.
Debugging Production
Debugging production servers is always trickier. You don’t have access to the Symfony profiler for instance. Logs are less verbose. But tailing the logs is possible:
You can even connect via SSH on the web container:
Don’t worry, you cannot break anything easily. Most of the filesystem is read-only. You won’t be able to do a hot fix in production. But you will learn a much better way later in the book.
Источник
Video not working?
It looks like your browser may not support the H264 codec. If you’re using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.
Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let’s us get back to making more videos :). But as always, please feel free to message us.
To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video
Make sure you’ve committed all of your changes — I already did. Because we’re about to install something super fun! Like, floating around space fun! Run:
The profiler — also called the «web debug toolbar» is probably the most awesome thing in Symfony. This installs a few packages and. one recipe! Run:
Ok cool! It added a couple of configuration files and even some routes in the dev environment only that help the profiler work. So. what the heck is the profiler? Go back to your browser, make sure you’re on the article show page and refresh! Voilà!
See that slick black bar at the bottom of the page! That’s the web debug toolbar! It’s now automatically injected at the bottom of any valid HTML page during development. Yep, this JavaScript code makes an AJAX call that loads it.
Oh, and it’s packed with info, like which route was matched, what controller was executed, execution time, cache details and even information about templates.
And as we install more libraries, we’re going to get even more icons! But the really awesome thing is that you can click any of these icons to go into. the profiler.
OoooOoo. This takes us to a totally different page. The profiler is like the web debug toolbar with a fusion reactor taped onto it. The Twig tab shows exactly which templates were rendered. We can also get detailed info about caching, routing and events, which we’ll talk about in a future tutorial. Oh, and my personal favorite: Performance! This shows you how long each part of the request took, including the controller. In another tutorial, we’ll use this to dig into exactly how Symfony works under the hood.
When you’re ready to go back to the original page, you can click the link at the top.
Magic with The dump() Function
But wait, there’s more! The profiler also installed Symfony’s var-dumper component. Find ArticleController and go to showAction() . Normally, to debug, I’ll use var_dump() to print some data. But, no more! Instead, use dump() : dump the $slug and also the controller object itself:
If you run into any memory issues or «ugly» dumped variables, just go to the next chapter, it will «fix» the issue. I found dump() which start infinite loop. Our Dear Sir explain in the next video let’s forsake this go to next video Yeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeees. FYI: In never versions of Symfony there is now dd($var);. This dump();’s your code and stops further execution. It’s the same as dump($var); and then die();. You’re right! The dd() helper method was introduced in Symfony 4.1. Thanks for sharing this useful tip for others. Hi! Thank you for this course, I didn’t where to start with symfony before. Thanks 🙂 Thanks for the reply, I manage to find the issue by myself finaly, it was a small mistake but very annoying. Ha! nice catch man 🙂 Tried to get this tutorial going but errors out of the box. The only deviation from the course install instructions is I’m using Docker for the database. Here are the errors shown in the local webserver log as soon as I try to visit the homepage. [Web Server ] Mar 17 17:53:58 |ERROR | SERVER GET (500) / ip=»127.0.0.1″ [Application] Mar 17 21:53:58 |CRITICA| PHP Uncaught Error: Argument 1 passed to SensioBundleFrameworkExtraBundleRequestParamConverterDoctrineParamConverter::__construct() must be an instance of DoctrineCommonPersistenceManagerRegistry or null, instance of DoctrineBundleDoctrineBundleRegistry given, called in C: Источник Adblock |
Непредвиденная ошибка
Часто при установке Symfony, после установке компонентов возникает ошибка подобно той с которой я сам столкнулся, а именно — не подхватывался Debugger.
На месте Debagger’а была ошибка:
An error occurred while loading the web debug toolbar.
В своей конфигурации я использовал Apache 2.4, PHP7.2. Настройка была обычной и не предвещающей ничего, однако «что то пошло не так».
Однако, хочу заметить, что при запуске сервера через консоль:
php bin/console server:run
Сервер запускался, а на экране внизу был заветный Debugger.
И как оказалось, проблема была, что не правильно шли запросы в директорию /_wdt/, а точнее сервер ее просто не видел.
Поправил я следующим образом, тем более что файла .htaccess в корне проекта я не увидел.
Решение
Решение было следующим: добавить файл .htaccess со следующим содержимым:
DirectoryIndex index.php <IfModule mod_negotiation.c> Options -MultiViews </IfModule> <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::2$ RewriteRule ^(.*) - [E=BASE:%1] RewriteCond %{HTTP:Authorization} . RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteRule ^index.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L] RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^ - [L] RewriteRule ^ %{ENV:BASE}/index.php [L] </IfModule> <IfModule !mod_rewrite.c> <IfModule mod_alias.c> RedirectMatch 307 ^/$ /index.php/ </IfModule> </IfModule>
После чего, сервер отдавал нужные мне запросы.
Надеюсь это помогло вам с вашей проблеме!
Удачи.
Make sure you’ve committed all of your changes — I already did. Because we’re about to install something super fun! Like, floating around space fun! Run:
composer require profiler --dev
The profiler — also called the «web debug toolbar» is probably the most awesome thing in Symfony. This installs a few packages and… one recipe! Run:
Ok cool! It added a couple of configuration files and even some routes in the dev
environment only that help the profiler work. So… what the heck is the profiler? Go back to your browser, make sure you’re on the article show page and refresh! Voilà!
See that slick black bar at the bottom of the page! That’s the web debug toolbar! It’s now automatically injected at the bottom of any valid HTML page during development. Yep, this JavaScript code makes an AJAX call that loads it.
Oh, and it’s packed with info, like which route was matched, what controller was executed, execution time, cache details and even information about templates.
And as we install more libraries, we’re going to get even more icons! But the really awesome thing is that you can click any of these icons to go into… the profiler.
OoooOoo. This takes us to a totally different page. The profiler is like the web debug toolbar with a fusion reactor taped onto it. The Twig tab shows exactly which templates were rendered. We can also get detailed info about caching, routing and events, which we’ll talk about in a future tutorial. Oh, and my personal favorite: Performance! This shows you how long each part of the request took, including the controller. In another tutorial, we’ll use this to dig into exactly how Symfony works under the hood.
When you’re ready to go back to the original page, you can click the link at the top.
Magic with The dump() Function
But wait, there’s more! The profiler also installed Symfony’s var-dumper
component. Find ArticleController
and go to showAction()
. Normally, to debug, I’ll use var_dump()
to print some data. But, no more! Instead, use dump()
: dump the $slug
and also the controller object itself:
|
… lines 1 — 8 |
class ArticleController extends AbstractController | |
{ | |
|
… lines 11 — 21 |
public function show($slug) | |
{ | |
|
… lines 24 — 28 |
dump($slug, $this); | |
|
… lines 30 — 34 |
} | |
} |
Ok, refresh! Beautiful, colored output. And, you can expand objects to dig deeper into them.
Tip
To expand all the nested nodes just press Ctrl
and click the arrow.
Using dump() in Twig
The dump()
function is even more useful in Twig. Inside the body
block, add {{ dump() }}
:
|
… lines 1 — 4 |
{% block body %} | |
{{ dump() }} | |
|
… lines 7 — 29 |
{% endblock %} |
Tip
If you don’t have Xdebug installed, this might fail with a memory issue. But don’t
worry! In the next chapter, we’ll install a tool to make this even better.
In Twig, you’re allowed to use dump()
with no arguments. And that’s especially useful. Why? Because it dumps an associative array of all of the variables you have access to. We already knew we had title
and comments
variables. But apparently, we also have an app
variable! Actually, every template gets this app
variable automatically. Good to know!
But! Symfony has even more debugging tools! Let’s get them and learn about «packs» next!
What PHP libraries does this tutorial use?
// composer.json
{
"require": {
"php": "^7.1.3",
"ext-iconv": "*",
"sensio/framework-extra-bundle": "^5.1", // v5.1.3
"symfony/asset": "^4.0", // v4.0.3
"symfony/console": "^4.0", // v4.0.14
"symfony/flex": "^1.0", // v1.17.6
"symfony/framework-bundle": "^4.0", // v4.0.14
"symfony/lts": "^4@dev", // dev-master
"symfony/twig-bundle": "^4.0", // v4.0.3
"symfony/web-server-bundle": "^4.0", // v4.0.3
"symfony/yaml": "^4.0" // v4.0.14
},
"require-dev": {
"easycorp/easy-log-handler": "^1.0.2", // v1.0.4
"sensiolabs/security-checker": "^5.0", // v5.0.3
"symfony/debug-bundle": "^3.3|^4.0", // v4.0.3
"symfony/dotenv": "^4.0", // v4.0.14
"symfony/monolog-bundle": "^3.0", // v3.1.2
"symfony/phpunit-bridge": "^3.3|^4.0", // v4.0.3
"symfony/profiler-pack": "^1.0", // v1.0.3
"symfony/var-dumper": "^3.3|^4.0" // v4.0.3
}
}
Я работаю на CentOS.
Я следовал за учебниками:
-
http://symfony.com/doc/current/best_practices/creating-the-project.html
-
https://symfony.com/doc/current/page_creation.html
Поскольку я использую Apache, я тоже следил за этой страницей:
- https://symfony.com/doc/current/setup/web_server_configuration.html
Я сделал контроллер по умолчанию и шаблон по умолчанию. С этим контроллером (/) я получаю следующую ошибку (на панели инструментов отладки):
An error occurred while loading the web debug toolbar. Open the web profiler.
Когда я нажимаю на ссылку «Открыть веб-профилировщик», я вижу ответ Apache:
Not Found
The requested URL /_profiler/177403 was not found on this server.
В инспекторе хрома я вижу:
ПОЛУЧИТЬ http://172.31.18.7/_wdt/177403 404 Не Найдено)
Вот интересная часть моего composer.json:
"require": {
"php": "^7.1.3",
"ext-iconv": "*",
"doctrine/doctrine-fixtures-bundle": "^3.0",
"sensio/framework-extra-bundle": "^5.1",
"sonata-project/admin-bundle": "^3.35",
"sonata-project/doctrine-orm-admin-bundle": "^3.6",
"symfony/apache-pack": "^1.0",
"symfony/console": "^4.0",
"symfony/flex": "^1.0",
"symfony/framework-bundle": "^4.0",
"symfony/lts": "^4@dev",
"symfony/maker-bundle": "^1.4",
"symfony/orm-pack": "^1.0",
"symfony/requirements-checker": "^1.1",
"symfony/security-bundle": "^4.0",
"symfony/twig-bundle": "^4.0",
"symfony/validator": "^4.0",
"symfony/yaml": "^4.0"},
"require-dev": {
"sensiolabs/security-checker": "^4.1",
"symfony/dotenv": "^4.0",
"symfony/web-profiler-bundle": "^4.0"},
мой httpd.conf:
<VirtualHost *:80>
DocumentRoot /var/www/html/elora/public
ServerName eloradev
ServerAlias www.elora.dev
DirectoryIndex index.php
<Directory "elora/public">
AllowOverride all
Order Allow,Deny
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
</Directory>
<Directory elora>
Options FollowSymlinks
</Directory>
ErrorLog /var/apache/logs/error.log
CustomLog /var/apache/logs/access.log combined
</VirtualHost>
И мой .htaccess:
DirectoryIndex index.php
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteCond %{HTTP:Authorization} .
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^index.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
RewriteRule ^ %{ENV:BASE}/index.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
<IfModule mod_alias.c>
RedirectMatch 307 ^/$ /index.php/
</IfModule>
</IfModule>
И, чтобы закончить, мой / счастливый / номер (https://symfony.com/doc/current/page_creation.html) поднимает сообщение apache:
Not Found
The requested URL /lucky/number was not found on this server.
Похоже, компонент маршрутизации не работает.
Правила маршрутизатора (отладка: маршрутизатор):
-------------------------- -------- -------- ------ -------------------
Name Method Scheme Host Path
-------------------------- -------- -------- ------ -----------------------
app_homepage ANY ANY ANY /
app_lucky ANY ANY ANY /lucky
app_lucky_number ANY ANY ANY /lucky/number
_twig_error_test ANY ANY ANY /_error/{code}.{_format}
_wdt ANY ANY ANY /_wdt/{token}
_profiler_home ANY ANY ANY /_profiler/
_profiler_search ANY ANY ANY /_profiler/search
_profiler_search_bar ANY ANY ANY /_profiler/search_bar
_profiler_phpinfo ANY ANY ANY /_profiler/phpinfo
_profiler_search_results ANY ANY ANY /_profiler/{token}/search/results
_profiler_open_file ANY ANY ANY /_profiler/open
_profiler ANY ANY ANY /_profiler/{token}
_profiler_router ANY ANY ANY /_profiler/{token}/router
_profiler_exception ANY ANY ANY /_profiler/{token}/exception
_profiler_exception_css ANY ANY ANY /_profiler/{token}/exception.css
-------------------------- -------- -------- ------ -----------------------
Я вручную создал каталог / _wdt, но это ничего не изменило.
Я проверил ошибки с помощью debug: event-dispatcher, ничего особенного.
Я заметил, что кеш для профилировщика находится в этом каталоге: var / cache / dev / profiler / 03/74 / и называется 177403
Еще одна вещь, я запустил композитора с пользователем «root». И я использовал chown, чтобы сменить владельца моего проекта.
Вот часть моего файла .env:
###> symfony/framework-bundle ###
APP_ENV=dev
6
Решение
Другие решения
Поскольку ответ находится в комментарии, я повторяю это:
Вы пробовали URL http://www.elora.dev/index.php/_wdt/ ? У меня была похожая проблема, потому что перезапись URL была неправильной. — A.L
Это оно !
- /index.php не имеет проблем с панелью инструментов отладки
- /index.php/lucky/number works
Большое спасибо A.L
4
composer require symfony/apache-pack
Do you want to execute this recipe?
[y] Yes
[n] No
[a] Yes for all packages, only for the current installation session
[p] Yes permanently, never ask again for this project
(defaults to n): y
Хост-файл:
127.0.0.1 symfony01.com
127.0.0.1 www.symfony01.com
httpd-vhosts.conf:
<VirtualHost *:80>
ServerName symfony01.com
ServerAlias www.symfony01.com
DocumentRoot "c:/wamp64/www/symfony01/public"<Directory "c:/wamp64/www/symfony01/public/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
3
Il звучит как проблема записи в кэш. Сбой профилировщика / панели отладки, потому что отладочные данные записываются в папку кэша. Ваше приложение, вероятно, работает нормально в prod
среда.
Чтобы увидеть, если это ваша проблема, попробуйте запустить chmod -R 777 var/cache
, и попробуй еще раз.
«Лучшее исправление» зависит от вашей ОС. Не стесняйтесь добавлять дополнительную информацию, чтобы точно ответить, в противном случае вы можете взглянуть на документацию, связанную с Symfony Вот (устаревшая ссылка специально, они удалили ее из SF4 doc).
2
просто добавь :
FallbackResource /index.php
в настройках вашего каталога
<Directory "/Library/WebServer/Documents/Your_public_symfony_directory">
....
FallbackResource /index.php
....
</Directory>
1
I work on CentOS.
I’ve followed the tutorials :
-
http://symfony.com/doc/current/best_practices/creating-the-project.html
-
https://symfony.com/doc/current/page_creation.html
As I use Apache, I’ve followed this page too :
- https://symfony.com/doc/current/setup/web_server_configuration.html
I made a default controller and a default template. With this controller (/) I get the the following error (within the debug toolbar):
An error occurred while loading the web debug toolbar. Open the web profiler.
When I click on the link : «Open the web profiler», I can see the Apache response :
Not Found
The requested URL /_profiler/177403 was not found on this server.
In the chrome inspector, I can see :
GET http://172.31.18.7/_wdt/177403 404 (Not Found)
Here’s the interesting part of my composer.json :
"require": {
"php": "^7.1.3",
"ext-iconv": "*",
"doctrine/doctrine-fixtures-bundle": "^3.0",
"sensio/framework-extra-bundle": "^5.1",
"sonata-project/admin-bundle": "^3.35",
"sonata-project/doctrine-orm-admin-bundle": "^3.6",
"symfony/apache-pack": "^1.0",
"symfony/console": "^4.0",
"symfony/flex": "^1.0",
"symfony/framework-bundle": "^4.0",
"symfony/lts": "^[email protected]",
"symfony/maker-bundle": "^1.4",
"symfony/orm-pack": "^1.0",
"symfony/requirements-checker": "^1.1",
"symfony/security-bundle": "^4.0",
"symfony/twig-bundle": "^4.0",
"symfony/validator": "^4.0",
"symfony/yaml": "^4.0"
},
"require-dev": {
"sensiolabs/security-checker": "^4.1",
"symfony/dotenv": "^4.0",
"symfony/web-profiler-bundle": "^4.0"
},
my httpd.conf :
<VirtualHost *:80>
DocumentRoot /var/www/html/elora/public
ServerName eloradev
ServerAlias www.elora.dev
DirectoryIndex index.php
<Directory "elora/public">
AllowOverride all
Order Allow,Deny
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
</Directory>
<Directory elora>
Options FollowSymlinks
</Directory>
ErrorLog /var/apache/logs/error.log
CustomLog /var/apache/logs/access.log combined
</VirtualHost>
And my .htaccess :
DirectoryIndex index.php
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteCond %{HTTP:Authorization} .
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^index.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
RewriteRule ^ %{ENV:BASE}/index.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
<IfModule mod_alias.c>
RedirectMatch 307 ^/$ /index.php/
</IfModule>
</IfModule>
And, to finish, my /lucky/number (https://symfony.com/doc/current/page_creation.html) raises the apache message :
Not Found
The requested URL /lucky/number was not found on this server.
It looks like the routing component does’nt work.
The router rules (debug:router) :
-------------------------- -------- -------- ------ -------------------
Name Method Scheme Host Path
-------------------------- -------- -------- ------ -----------------------
app_homepage ANY ANY ANY /
app_lucky ANY ANY ANY /lucky
app_lucky_number ANY ANY ANY /lucky/number
_twig_error_test ANY ANY ANY /_error/{code}.{_format}
_wdt ANY ANY ANY /_wdt/{token}
_profiler_home ANY ANY ANY /_profiler/
_profiler_search ANY ANY ANY /_profiler/search
_profiler_search_bar ANY ANY ANY /_profiler/search_bar
_profiler_phpinfo ANY ANY ANY /_profiler/phpinfo
_profiler_search_results ANY ANY ANY /_profiler/{token}/search/results
_profiler_open_file ANY ANY ANY /_profiler/open
_profiler ANY ANY ANY /_profiler/{token}
_profiler_router ANY ANY ANY /_profiler/{token}/router
_profiler_exception ANY ANY ANY /_profiler/{token}/exception
_profiler_exception_css ANY ANY ANY /_profiler/{token}/exception.css
-------------------------- -------- -------- ------ -----------------------
I’ve manually created the directory /_wdt, in case, but it did’nt change anything.
I’ve checked errors with debug:event-dispatcher, nothing special.
I’ve noticed that the cache for the profiler is in that directory : var/cache/dev/profiler/03/74/ and is named 177403
One more thing, I’ve ran composer with the ‘root’ user. And I’ve used chown to change the owner of my project.
Here’s a part of my file .env :
###> symfony/framework-bundle ###
APP_ENV=dev