Creating the first controller in Symfony - php

I have just started to learn Symfony. The fact is that I do things and they work but I don't understand what I am doing and that must be the wrong way starting to learn something.
Here is a simple controller:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class HelloController extends Controller
{
/**
* #Route("/hello")
*/
public function helloAction() {
return $this->render('', array());
}
}
So in this case when I type
/**
* #Route("/hello")
*/
my editor automatically adds this line of code:
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
What is that doing?
I have learned that namespaces must match the directory path but there is no way I could find that path in my Symfony project. So is it outside of my project? If so, this will be good to know in case I want to upload my project on the web server.
I would appreciate if someone could please explain this "mystery".

Your IDE just added the dependency to Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;, which is required to use the #Route annotation.
It is placed under the vendor/ directory, which of course you will need to upload along with your sources.

Related

Laravel View Composer, cant seem to get it to work

so i have followed many tutorials and videos and checked here and cant seem to get this to work, really need help. im going to provide my code and explain what im trying to so and hopefully someone can help me sort this out. so what im trying to so is to pass my $user and $company data from my database to my partial layout though view composer. i used php artisan to make a composerserviceprovider and and dashboardcomposer in my view/composer folder and i get errors.
my composerserviceprovider.php is as follows
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use App\companies;
use App\user;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
view()->composer("layouts.dashboard","App\View\Composers\dashboardnavComposer");
}
}
my dashboardnavcomposer.php is as follows
<?
namespace App\View\Composers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use App\companies;
use App\user;
class dashboardnavComposer
{
public function compose(View $view)
{
$view->with('user', ComposerServiceProvider::all());
}
}
im probably doing something completely wrong or completely missing a step, i already did the php artisan dumpautoload, so this is not the problem. any help would be appreciated. also to let you know, i use to do this 10+ years ago and i quit to be a truck driver and so last time i did this php4 was king. so please understand i just starting relearning this about 30 days ago.
thanks in advance for any help you can provide.
Not sure what you filename actually is for the composer but your filename should match the class name (exactly in case). The file should be named dashboardnavComposer.php. In reality the class should probably be more like DashboardNavComposer and the file would be DashboardNavComposer.php. Also make sure it is in the app/Views/Composers folder.
I am not sure why your View Composer is calling to a Service Provider, ComposerServiceProvider, though.
The PSR-4 autoloading should be picking up these new files. You can run composer dump just in case.

Routing annotation with Symfony4 doesn't match cause of DNS?

I'm trying to make the first page creating tutorial
https://symfony.com/doc/current/page_creation.html
So i use the annotation in my src/Controller/LuckyController.php
<?php
namespace App\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class LuckyController extends Controller
{
/**
* #Route("/lucky/number")
*/
public function number()
{
$number = mt_rand(0, 100);
return $this->render('lucky.html.twig', array(
'number' => $number,
));
}
}
And when i try to go in this url
(i.e)OVHServer.fr/project/public/lucky/number
I got a 404 Not Found Error
I guess that it's because I didn't put my DNS in the the project/public directory but I want to know if you know a way for let the Url like that and get the road in my controller.
Thank's
DNS is not relevant. The routing takes effect after the configuration of the server.
The public directory of symfony 2 and 3 is named web, it's named public since symfony4
For example :
OVHServer.fr/app.php/lucky/number
OVHServer.fr/web/app.php/lucky/number
OVHServer.fr/project/public/app.php/lucky/number
When your server is configured to hide the app.php it would give you
OVHServer.fr/lucky/number
OVHServer.fr/web/lucky/number
OVHServer.fr/project/public/lucky/number

Symfony4: No route found for "GET /lucky/number"

I am starting to play with symfony4. I've just created new application and create new LuckyController. It works with routes.yaml configured in this manner:
lucky:
path: /lucky/number
controller: App\Controller\LuckyController::number
With the following controller:
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
class LuckyController
{
public function number()
{
return new Response('<html><head></head><body>' . rand(111, 999) . '</body></html>');
}
}
But I want to use annotations. So I decided to comment routes.yaml. Following documentation that explain how to create a route in symfony I've made this:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class LuckyController extends Controller
{
/**
* #Route("/lucky/number")
*/
public function number()
{
return new Response('<html><head></head><body>' . rand(111, 999) . '</body></html>');
}
}
Sometimes this problem occurs because of cache.you need to run php bin/console cache:clear.then it will work fine.
In Symfony4 you have to install annotations bundle.
Run this command composer require annotations
Then restart Your project.
I had the same thing when trying the annotations, then I found out with the demo installed (the blog) you need to add the language in the URL. So the documentation says:
http://localhost:8000/lucky/number will work exactly like before
That did not work. This however did:
http://localhost:8000/en/lucky/number
As suggested in #Jack70 answer.
https://127.0.0.1:8000/en/random/number
This should work.
If you run the command php bin/console debug:router it would show you the list of routes available as you can see in that list, you need to add the locale (language) as first argument.
app_annotationsample_number ANY ANY ANY /{_locale}/random/number
If you use annotations - you need check config/routes/anotations.yaml.
You need check path to your controller or add new path, for example:
controllers:
resource: ../../src/Controller/
type: annotation
Also, you'll get that error if the route name appears more than once.
I ran into that error while developing Angular app, so in order to debug I tried that same route in Postman, which I knew used to work fine, but this time it did not throwing the mentioned error. Luckily, I have just added one new controller, so finding the culprit was easy: the problem was that after copying methods from web controller to api controller I forgot to change route name in one of the methods.
So you might wanna be careful when copying :)

PHP Symfony error: "did you forget to use a use statement", regardless of class/function

I have started building a new Web App using Symfony, but am having issues using classes.
PhpStorm is able to find the functions within the classes (due to the fact that it gives suggestions when you type $className->.
Also, to prove this is not the same as the other similar questions, I have over simplified it, and even so, the error still occurs.
I have the below in my DefaultController:
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use testBundle;
use AppBundle\domainionClasses\firstlevelchecks;
class DefaultController extends Controller
{
/**
* #Route("/register",name="register")
*/
public function registerAction(){
$testClass = new firstlevelchecks();
$testing = $testClass->donothing(); //the IDE knows that the function donothing() exists, in fact it suggests it.
return new Response('');
}
}
The below is the php class located in AppBundle/domainionClasses/test1.php
<?php
namespace AppBundle\domainionClasses;
class firstlevelchecks
{
function donothing(){
return null;
}
}
When loading the /register route, the below Symfony error is displayed:
Attempted to load class "firstlevelchecks" from namespace "AppBundle\domainionClasses".
Did you forget a "use" statement for another namespace?
It is attempting to load the class from the correct name space, and I have used a use statement.
Is there anything I am missing here, or is there a problem with Symfony? This is the first time I used the new version of PhpStorm, and have just downloaded the plugin, also the first time I have experienced this issue :(
Because your file is named test1.php, how can the autoloader know which file to include ?
You shoud rename it to firstlevelchecks.php (= the name and case of your class).

Attempted to load class "ClassName" from namespace (...). Even though namespace is imported

I have a Symfony project to which I added some non-symfony php files containing various classes. But for some reason the classes are not loaded when loading the website, even though the IDE sees them properly.
So, I have a class that needs other classes:
namespace rootspace\FrontBundle\Controller;
use rootspace\FrontBundle\Networks\TwitterOAuth;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class TwitterController extends Controller
{
public function connectAction(){
// The TwitterOAuth instance
$connection = new TwitterOAuth('abc', '123');
}
}
And then the class which fails to load (that needs yet another file)
namespace rootspace\FrontBundle\Networks;
/* Load OAuth lib. You can find it at http://oauth.net */
//require_once('OAuth.php'); -- should this be commented out?
/**
* Twitter OAuth class
*/
class TwitterOAuth {
/* Contains the last HTTP status code returned. */
}
Lastly, the third file
namespace rootspace\FrontBundle\Networks;
use Symfony\Component\Config\Definition\Exception\Exception;
class OAuthConsumer
{
public $key;
public $secret;
}
(...)
I assume the actual filenames don't matter, right? Nor their structure? PhpStorm sees all the classes properly, I can right-click through them, but it fails when deployed.
Thanks for help
Edit - the whole error message says
Attempted to load class "TwitterOAuth" from namespace "rootspace\FrontBundle\Networks" in D:\Dropbox\project\src\rootspace\FrontBundle\Controller\TwitterController.php line 15. Do you need to "use" it from another namespace?
This is because Symfony's autoloader follows PSR standards (PSR-0, PSR-4) which says that fully qualified (with namespace) class name translates to file location and name. So in fact file names does matter.
So in your case rootspace\FrontBundle\Networks\TwitterOAuth class should be located in rootspace/FrontBundle/Networks directory in file called TwitterOAuth.php
If classes you are using does not follow PSR standards you can also register them manually in app/autoloader.php file
Check these for more info:
How can I add a namespace to Symfony 2.1?:
How to autoload class
And check this answer
I forgot to add a .php extension to my filename

Categories