Chapters
-
Course Code
Subscribe to download the code!
Subscribe to download the code!
-
This Video
Subscribe to download the video!
Subscribe to download the video!
-
Course Script
Subscribe to download the script!
Subscribe to download the script!
Databases and Doctrine
Scroll down to the script below, click on any sentence (including terminal blocks) to jump to that spot in the video!
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
Symfony doesn't care about your database or the code you use to talk to it.
Seriously. It's not trying to be rude, but other libraries already solve
this problem. So if you want to make a :phpclass:PDO
connection and run
raw SQL queries, that's great! When we create services in Episode 3, you'll
learn some life-saving strategies to organize something like this.
But most people that use Symfony use a third-party library called Doctrine. It has its own website and documentation, though Symfony's Doctrine documentation is a lot friendlier.
In a nutshell, Doctrine maps rows and columns in your database to objects
and properties in PHP. Imagine we have an Event
object with name
and location
properties. If we tell Doctrine to save this object, it
inserts a row into a table and puts the data on name
and location
columns. And when we query for the event, it puts the column data back onto
the properties of an Event object.
The big confusing mind-switch is to stop thinking about tables and start thinking about PHP classes.
Creating the Event Entity Class
In fact, let's create the Event
class we were talking about. The console
can even make this for us with the doctrine:generate:entity
command:
php app/console doctrine:generate:entity
Like other commands, this one is self-aware and will start asking you questions.
In step 1, enter EventBundle:Event
. This is another top-secret shortcut
name and it means you want the Event
class to live inside the EventBundle
.
Now, choose annotation as the configuration format and move on to field creation. Add the following fields:
name
as a string field;time
as a datetime field;location
as a string field;- and
details
as a text field.
These types here are configuration that tell Doctrine how each property should be stored in the database.
If you messed anything up, panic! Or just exit with ctrl+c
try the command
again. Nothing happens until it finishes.
Tip
All of the Doctrine data types are explained in their documentation: Doctrine Mapping Types.
Say "yes" for the repository class and confirm generation. A repository is a cool guy we'll use later to store custom queries.
What just Happened?
Ok! So what did that do? Actually, it just created 2 new classes in an Entity
directory in our bundle. And that's it.
Check out the new Event
class:
// src/Yoda/EventBundle/Entity/Event.php
namespace Yoda\EventBundle\Entity;
/**
* @ORM\Table()
* @ORM\Entity(repositoryClass="Yoda\EventBundle\Entity\EventRepository")
*/
class Event
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
// ...
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
// ...
}
For Doctrine, the word "entity" means a normal PHP class that we will save to the database. So, whenever I say "entity", just scream: "that's just a normal PHP class!". Your co-workers will love you!
If you ignore the PHP comments, you'll see that this is a plain old PHP class.
It doesn't do anything: it just stores data on its private properties. Getter
and setter methods - like getName()
and setName()
- were generated
so we can play with an event's data. It's underwhelming, almost disappointing,
and that's what makes Doctrine so interesting.
Now, check out the PHP comments above the class. These comments are called "annotations", and they're actually read and parsed by Doctrine. So when you hear "annotations", shout "PHP comments that are read like configuration!".
These tell Doctrine how it should save an Event
object to the database.
Right now, they will save to an event
table and each property will be
a column in that table. I usually like to prefix all of my table names, so
let's do that by adding a name option to the Table
annotation:
/**
* @ORM\Table(name="yoda_event")
* @ORM\Entity(repositoryClass="Yoda\EventBundle\Entity\EventRepository")
*/
class Event
{
// ...
}
Creating the "play" Script
We're ready to insert data, but first I want to show you a debugging trick.
First, copy the web/app_dev.php
file to the root of the project and
rename it to play.php
:
cp web/app_dev.php play.php
Open it up and remove the IP protection stuff at the top and update the require paths since we moved things around:
// play.php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
umask(0000);
$loader = require_once __DIR__.'/app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/app/AppKernel.php';
// ...
This script boots Symfony, processes the request, and spits out the page. But I have evil plans to transform it into a debugging monster where we can write random code and execute it from the command line to see what happens.
Replace the last three lines with $kernel->boot()
:
// ...
require_once __DIR__.'/app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$kernel->boot();
Remember the service container from earlier? We have access to it here. To make it as flexible as possible, I'll add a few lines that help fake a real request. This is a little jedi mind trick so don't worry about what these do right now:
// play.php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
umask(0000);
$loader = require_once __DIR__.'/app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$kernel->boot();
$container = $kernel->getContainer();
$container->enterScope('request');
$container->set('request', $request);
// all our setup is done!!!!!!
Our evil creation is alive! So let's play around. How could we render a template
here? Why, just by grabbing the templating
service and using its render()
method:
// ...
// all our setup is done!!!!!!
$templating = $container->get('templating');
echo $templating->render(
'EventBundle:Default:index.html.twig',
array(
'name' => 'Yoda',
'count' => 5,
)
);
Execute the play script from the command line.
php play.php
When I run it, the template is rendered and printed out. How cool is that? This is perfect for whenever we need to quickly test out some code.
54 Comments
Hey Pete,
I suppose you're on Windows, right? Unfortunately, weird things could occur on Windows... :( What PHP server do you use? Could you restart it and repeat? Also could content to the DB in your Symfony application (I mean not in console but fetch any existent data from DB in code, i.e. get any entity from DB)? Does it work for you?
Cheers!
Hi Victor thanks for your message, nope I'm on OS X! Currently I'm just using a local server - could that be the issue? Don't think so as this tutorial uses local and seems to run fine. Iv never sent any data to the DB (MySQL freshly installed). Any thoughts on why it's just hanging at the generate entity nickname command?
Oh, I see... OK, I'm on Mac too, so I can tell you a bit about my workflow: I installed with brew package manager "mysql" and "php70" packages - it will be enough for local development for this course, and actually for most our courses too. Also I additionally installed a few php extensions with brew for Symfony project: php70-intl, php70-xdebug, php70-opcache. Then brew manager should do other work for you.
When you install a package with brew - look closely to the output, it could has some additional instructions. You can see more information about installed package with "brew info %package%", e.g. "brew info mysql" show you information about mysql server, and at the end of the output you could see that you can start MySQL server with "mysql.server start" command.
So I think you need to start it manually at first, and then try to connect to the DB manually with such tool as MySQL Workbench or better SequelPro which I like more: https://github.com/sequelpr... . It's a free MySQL database management tool for Mac OS X. If you could connect to your MySQL server (create DB, tables, etc.). And if it works fine - try to connect to the DB from your Symfony application using the same credentials which you used in SequelPro. Let me know if you have any issues with this workflow.
Cheers!
I'll also add that the "freezing" you're getting is VERY odd - I don't understand why that would be happening, and it's very possible that your database is setup just fine (or, it's possible that it could be a MySQL connection error... though I would expect that to have an error, not freeze).
By the way - the tutorial you're going through is a bit outdated! But there is a newer version you can find here, which might be a bit more useful! http://knpuniversity.com/sc...
Cheers!
OK thanks Victor... seems like iv pinched forward again - managed to manually start the sql server as you suggested. also got the info on it (below). Same issue though when I got to create an entity. Ryan maybe I used the wrong word when I said freeze, everything still works fine and is responsive, just that it never gets any further than the below. Just sits there.
petergarvin (master) PHPtodo $ brew info mysql
mysql: stable 5.7.16 (bottled)
Open source relational database management system
https://dev.mysql.com/doc/r...
Conflicts with: mariadb, mariadb-connector-c, mysql-cluster, mysql-connector-c, percona-server
/usr/local/Cellar/mysql/5.7.16 (13,511 files, 439M) *
Poured from bottle on 2016-11-14 at 08:37:37
From: https://github.com/Homebrew...
==> Dependencies
Build: cmake ✘
Required: openssl ✔
==> Requirements
Required: macOS >= 10.7 ✔
==> Options
--with-archive-storage-engine
Compile with the ARCHIVE storage engine enabled
--with-blackhole-storage-engine
Compile with the BLACKHOLE storage engine enabled
--with-debug
Build with debug support
--with-embedded
Build the embedded server
--with-local-infile
Build with local infile loading support
--with-test
Build with unit tests
==> Caveats
We've installed your MySQL database without a root password. To secure it run:
mysql_secure_installation
To connect run:
mysql -uroot
To have launchd start mysql now and restart at login:
brew services start mysql
Or, if you don't want/need a background service you can just run:
mysql.server start
petergarvin (master) PHPtodo $ mysql.server start
Starting MySQL
. SUCCESS!
petergarvin (master) PHPtodo $ php app/console doctrine:generate:entity
Welcome to the Doctrine2 entity generator
This command helps you generate Doctrine2 entities.
First, you need to give the entity name you want to generate.
You must use the shortcut notation like AcmeBlogBundle:Post.
The Entity shortcut name: EventBundle:Task
Yo Pete!
Ok, 2 things!
1) Let's make sure MySQL is running. Try running this from the terminal:
mysql -u root
If this connects to the MySQL terminal, you are in business :). If not, try the brew services start mysql
command.
2) To make sure that PHP can see MySQL, try running this command:
php app/console doctrine:database:create
Does that create a database (or at least say "Database already exists")?
3) About the generator task - I just want to make sure: after you type EventBundle:Task
, are you pressing enter? I'm positive you are, just double-checking! When you try this task again, try running with in "very verbose" mode, so:
php app/console doctrine:generate:entity -vvv
This may give you more log output on the screen before it "freezes".
Let us know what you find out!
Thanks Ryan. So I've done all of that. Good news is it looks like sql is working... bad news is the problem hasn't gone.
Output from 1):
petergarvin (master) PHPtodo $ mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.16 Homebrew
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Output from 2):
petergarvin (master) PHPtodo $ php app/console doctrine:database:create
Command just didn't do anything - prompt never re-appeared. Nothing else happened.
from 3) Yep I am pressing return (i know the output doesn't always look like it). Tried the -vvv command and same thing happened:
petergarvin (master) PHPtodo $ php app/console doctrine:generate:entity -vvv
Welcome to the Doctrine2 entity generator
This command helps you generate Doctrine2 entities.
First, you need to give the entity name you want to generate.
You must use the shortcut notation like AcmeBlogBundle:Post.
The Entity shortcut name: EventBundle:Task
Again, just sits there - nothing happening
Also I should say - in all instances where it 'freezes' or nothing happens, I use ctrl+C to quit out and get the prompt back. Feels like that suggests I'm 'in' something?
Hey Pete,
I have a few more instructions for you, perhaps something could help us:
Could you show us content of your current app/config/parameters.yml file? (please, note, the parameters.yml not parameters.yml.dist)?
I suppose you installed PHP first, then MySQL. Since MySQL is working on your machine, could you reinstall php? Maybe brew will fix some missing configuration in this case. Try this command:
brew reinstall homebrew/php/php70 --force
(for me it's php70, but use your version of PHP you have already installed) and look closely to the output. Probably you'll get some suggestion from brew.Could you try to use "database_host: localhost" instead of 127.0.0.1 in app/config/parameters.yml? But right after this change manually remove app/cache/dev and app/cache/prod folders first and only then try to run console command which is freeze for you before. If nothing happen - I think better revert it to the 127.0.0.1 IP then.
What about to specify explicitly the environment for running command? Please run the same command in dev env:
php app/console doctrine:database:create --env=dev
. Probably you should see some errors in the output instead of freeze. Then try the same command in prod:php app/console doctrine:database:create --env=prod
. Is there any difference?And the last, could you check another project? Probably you have something corrupted in the current one. I'd recommend you to download a clear Symfony SE app. Here's a few instruction how to install it: http://symfony.com/download . First, install the Symfony Installer. Then, execute this command:
symfony new my_project
. And then from my_project folder run the server at first:php bin/console server:run
. Is it work? Do you see the "Welcome" message when you open localhost:8000 ? If server works - that's very good! Then try to executephp bin/console doctrine:database:create
? Is it still freeze too?
Cheers!
Just to follow on up on what Victor is suggesting: basically, your computer/application is behaving VERY strangely. It seems that when PHP talks to MySQL, it "freezes". That was proven when it also froze while running the doctrine:database:create command. Neither of us have seen anything like this before, nor can we find anything on Google about it! You seem to have stumbled over something very odd!
Ryan, I think the company I am interested in uses the latest stable version of Symphony - am I right in thinking that is v2.8? If so I'm guessing the Symphony 3 tutorial isn't what I want?
Hey Pete!
Ah, I understand! So, the version of Symfony that you *probably* want is Symfony 3 (current stable is Symfony 3.1). But, it's a bit more interesting that that. You see, Symfony's latest stable release is 3.1, and in a few weeks, the stable 3.2 will be released. However, the latest long-term support (LTS) release is still 2.8. The next LTS Will be Symfony 3.4, released at the end of Nov 2017. Typically, if you're starting a new project, you will just want the latest release (3.1). But sometimes, if you have a big enterprise project that you know you won't be able to upgrade any time soon, then you will choose the LTS release. The difference is that the LTS is supported for longer. You can even see information about when releases are supported on this page: http://symfony.com/roadmap. So, for example, if you started a Symfony 2.8 project, you will receive bug fixes until Nov 2018 (then you will need to upgrade to the new LTS, 3.4 at that time). But, if you started a Symfony 3.1 project, you will receive bug fixes until only Jan 2017 (for 3.2, it will be July 2017). This means that to stay on a supported version, you'll need to upgrade Symfony a bit more frequently. That's less of a big deal than it sounds like: upgrading "minor" versions (e.g. 3.1 to 3.2, or 3.2 to 3.3) is very easy because Symfony protects against backwards-compatibility breaks.
SO, the choice is your's :). But, I would still probably recommend going through the Symfony 3 tutorial, even if you'll use Symfony 2.8 (or better, go through both tutorials eventually). Not much changed between Symfony 2 and 3, but the newer tutorials are updated for current best-practices, etc. The only thing that you'll need to "translate" from the Symfony 3 tutorials back to a Symfony 2 project is a slight directory structure change, e.g. app/console in Symfony2 was renamed to bin/console. We talk about these changes here: https://knpuniversity.com/s...
Let me know if this helps!
Also, if I quit the server while the entity generator is hanging, I get the following:
$ php app/console doctrine:generate:entity
Welcome to the Doctrine2 entity generator
This command helps you generate Doctrine2 entities.
First, you need to give the entity name you want to generate.
You must use the shortcut notation like AcmeBlogBundle:Post.
The Entity shortcut name: EventBundle:Event
[Doctrine\DBAL\Exception\DriverException]
An exception occured in driver: SQLSTATE[HY000] [2006] MySQL server has gon
e away
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[HY000] [2006] MySQL server has gone away
[PDOException]
SQLSTATE[HY000] [2006] MySQL server has gone away
[Symfony\Component\Debug\Exception\ContextErrorException]
Warning: PDO::__construct(): MySQL server has gone away
doctrine:generate:entity [--entity ENTITY] [--fields FIELDS] [--format FORMAT] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command>
Hi,
I am new to symfony. Started learning.
I am using windows environmnet. Sysmfony 2.6 version.
While trying ot create entity getting error as below.
[Doctrine\DBAL\Exception\ConnectionException]
An exception occured in driver: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)
[PDOException]
SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)
Hi Sekhar M.
It looks like your database access is not configured. Check your `app/config/parameters.yml` there should be database credentials configured you need to set proper database_user and database_password.
Cheers!
after entering the Entity shortcut name I get...
[Doctrine\DBAL\Exception\ConnectionException]
An exception occured in driver: SQLSTATE[HY000] [1049] Unknown database 'symfony'
Hey Justice!
Your database doesn't exist yet - so don't forget to have Symfony create it for you :). This is explained in the next chapter: https://knpuniversity.com/s...
Cheers!
Hi!
I must say that I'm not only reading the tutorial but trying to reproduce all steps manually. So it's strange that I need to flashforward into the next article to setup database properly.
Hey connectscape!
Actually, you're 100% correct! And the tutorial *is* built so you can follow along. Well, at least it *was* :). Due to a change in Doctrine, you are forced to create your database *earlier* than you did previously. So, when this tutorial was written, we were able to complete this chapter without (yet) needing to worry about the database. But after the change in Doctrine, it became necessary (in many cases) to create the database one step earlier. An unfortunate change, really :).
Also, if you're interested in the newer version of this tutorial, check out https://knpuniversity.com/s...
Cheers!
I was running MySQL via XAMPP. I manually added a DB named "symfony". then ran the command via the command line again. That seems to have fixed it.
Hey there!
First of all thank you so much for these amazing tutorials! :) I really fell in love with them!
running the play.php with symfony 2.8 I get the following:
PHP Fatal error: Class 'Symfony\Component\Debug\Debug' not found in /Users/maxschons/Sites/knpuniversity2/play.php on line 9
PHP Stack trace:
PHP 1. {main}() /Users/maxschons/Sites/knpuniversity2/play.php:0
Fatal error: Class 'Symfony\Component\Debug\Debug' not found in /Users/maxschons/Sites/knpuniversity2/play.php on line 9
Call Stack:
0.0016 229856 1. {main}() /Users/maxschons/Sites/knpuniversity2/play.php:0
Any idea? Thx!
Hi Max!
Awesome - so glad you're finding the tutorials useful! :D
Now, about your error. It's interesting... the class you mentioned DOES exist in Symfony 2.8 (https://github.com/symfony/.... So, the problem is related to autoloading somehow. Which file are you requiring on top - app/autoload.php or app/bootstrap.php.cache? There's a subtle difference between the two starting in Symfony 2.8 (we tweaked some directory structure things in Symfony). If in doubt, copy the web/app_dev.php file from *your* project as your starting point for the play.php file (instead of making your copy look exactly like mine).
If you're still having trouble, just post your full play.php file - and also, post the "autoload" section of your composer.json - and we'll work it out :).
Cheers!
Hey Ryan!
It worked using the /app/autoload.php require statement! Awesome! :D Thank you so much for your quick and detailed reply!
Cheers!
Max
Woohoooo! Now keep rocking!
Hey there!
I have a question about entities id's column
I already have an users table in my project and it's ID is not an "AUTO_INCREMENT" id, it is a custom varchar ID
Is it possible to change the auto generated ID column of Doctrine to this one ?
Thanks for your time! :]
Hmm, you know, I'm not sure :). But I would try it! Remove the `$id` (the normal one that Doctrine adds), then add a property for your varchar one that exists, and give it @ORM\Column and @ORM\Id, but don't give it @ORM\GeneratedValue. I think in theory that should work. Doctrine needs (I believe) someething to be the @ORM\Id of the entity, but really, it doesn't care if it's an integer or auto-increment. Not having auto-increment causes other problems of course: specifically you need to manually set this before saving.
Let me know how it goes!
I did what you said and it worked!
I just added a "generateId" method to my repository and made my listener to call it on PrePersist event
Thanks for your time :D
Quite disappointing actually, frankly speaking... :( "Let's change that, we don't need this, let's create play.php"...
Come on! The framework is quite overwhelming as it is, so go with the default flow first, explain everything and only then (possibly) try to introduce some "tricks".
I hope your Symfony 3 tutorials are better.
Hey Maksym!
Hmm, sorry you're disappointed! If I do something different than the "norm", it's usually to show something in the easier, more "pure" way first, and then later we build on the complexity (instead if building the "normal", but more complex thing first). It's definitely not my intention to be extra fancy - quite the opposite!
And there's a bit of history to this: I work on the Symfony core, and during much of Symfony2, sometimes we (the community) made things too hard. At times, I'll make things simpler in the tutorials because of this. Fortunately, over time, that's changed - a lot of easy-win simplifications have been adopted in Symfony 3 (really, many were adopted towards the end of Symfony2), and now I go "off-script" quite a bit less.
Anyways, I hope that gives you a bit of background! And if you have any questions about why I did something, or if you find anything specifically confusing, just ask and we'll be happy to have a conversation about that!
Cheers!
Well, ok, but the chapters I commented on were by Leanna...
Ah yes, voiced by Leanna, written by me :)
Wow, what a surprise... And I'm definitely not sure it's the right way. I believe the best tutorials are recorded by the authors themselves.
That's what we do on the newer tutorials, except for the beginner PHP or OO tutorials. But, I'm happy that this was a surprise - that's the point!
Cheers!
Very helpful tutorial
Hey everyone... very new to Symphony and pulling my hair out for the last few hours. I've been following the tutorials along thus far, and have got to the bit where we are using the doctrine entity generator... then I get the below when I try to name the entity:
```
$ php app/console doctrine:generate:entity
Welcome to the Doctrine2 entity generator
This command helps you generate Doctrine2 entities.
First, you need to give the entity name you want to generate.
You must use the shortcut notation like AcmeBlogBundle:Post.
The Entity shortcut name: EventBundle:Event
[Doctrine\DBAL\Exception\ConnectionException]
An exception occured in driver: SQLSTATE[HY000] [2002] Connection refused
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[HY000] [2002] Connection refused
[PDOException]
SQLSTATE[HY000] [2002] Connection refused
doctrine:generate:entity [--entity ENTITY] [--fields FIELDS] [--format FORMAT] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-s|--shell] [--process-isolation] [-e|--env ENV] [--no-debug] [--] <command>
```
I have had a look through forums and tried changing host to 'localhost' and changing the port number from null to 3306. Neither helped and I have reset these changes. Please help!
Hey Pete!
Welcome to Symfony :). So, you're correct that there's a problem talking to your MySQL database. Basically, "Connection Refused" means "I literally cannot find / connect to your database". Since you set host to localhost (which is correct, unless you have your database server running on a different server, which you likely don't for local dev!), I think that your MySQL database just simply isn't running. Did you install MySQL? What happens if you run this from the command line mysql -u root
?
Another alternative is to run your app using SQLite instead of MySQL, which you can do with some simpler configuration changes (I can help you out if you're interested). But, you probably want to get MySQL up, running and connected.
Cheers!
I also tried using the Sqlite technique from here that someone recommended: https://gist.github.com/wea...
Yo Pete!
Ah, just saw this after my reply (https://knpuniversity.com/s.... If you tried SQLite and still got connection refused, then I think there's still something not quite right with your SQLite configuration (i.e. Doctrine is still trying to talk to MySQL for some reason). And probably, it was because I had a bug in my gist! I just updated it - https://gist.github.com/wea... - the driver was incorrect.
Cheers!
thanks for coming back to me Ryan... embarassingly no, I haven't installed mysql... although to be fair the course never mentioned to do so! Guessing I just need the first download link from this page? http://dev.mysql.com/downlo...
To add - I just got it working with your new Gist :D Thanks for that - but as you say, may be a good idea to get mySql up and running properly
Hey Pete!
No worries :). You're right, we don't mention it. What operating system do you have, and how did you install PHP? The best answer for how to install varies based on operating system, and downloading it directly from the MySQL site (oddly enough) isn't the easiest solution on most systems.
Cheers!
Hey Ryan,
I don't know how I installed php, but I know I have PHP 5.5.36 (cli)
My Operating system is OS X El Capitan Version 10.11.6
Is that enough info?
Yo Pete!
This is absolutely enough! You're likely using the PHP that comes standard with OSX. Here's what I'd recommend to give you the best experience, and to be like "most" OSX users:
1) Install Homebrew
2) Use Homebrew to install php, e.g. brew install homebrew/php/php56
The advantage is that you can easily install php extensions and other libraries with Brew. For example, I would also install these things:
brew install homebrew/php/php56-apcu homebrew/php/php56-intl homebrew/php/php56-mcrypt homebrew/php/php56-opcache homebrew/php/php56-xdebug
And of course, we'll want to install MySQL!
brew install mysql
This should at least get you started! Let me know if you have any questions! After you install the first package (php56), read the details it tells you - it may give you a command or two to run so that your terminal knows to use your new php, and not the built-int PHP in OSX.
Cheers!
OK great thanks - making some progress! So after the first install - this was the message:
The php.ini file can be found in:
/usr/local/etc/php/5.6/php.ini
✩✩✩✩ Extensions ✩✩✩✩
If you are having issues with custom extension compiling, ensure that
you are using the brew version, by placing /usr/local/bin before /usr/sbin in your PATH:
PATH="/usr/local/bin:$PATH"
PHP56 Extensions will always be compiled against this PHP. Please install them
using --without-homebrew-php to enable compiling against system PHP.
✩✩✩✩ PHP CLI ✩✩✩✩
If you wish to swap the PHP you use on the command line, you should add the following to ~/.bashrc,
~/.zshrc, ~/.profile or your shell's equivalent configuration file:
export PATH="$(brew --prefix homebrew/php/php56)/bin:$PATH"
✩✩✩✩ FPM ✩✩✩✩
To launch php-fpm on startup:
mkdir -p ~/Library/LaunchAgents
cp /usr/local/opt/php56/homebrew.mxcl.php56.plist ~/Library/LaunchAgents/
launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.php56.plist
The control script is located at /usr/local/opt/php56/sbin/php56-fpm
OS X 10.8 and newer come with php-fpm pre-installed, to ensure you are using the brew version you need to make sure /usr/local/sbin is before /usr/sbin in your PATH:
PATH="/usr/local/sbin:$PATH"
You may also need to edit the plist to use the correct "UserName".
Please note that the plist was called 'homebrew-php.josegonzalez.php56.plist' in old versions
of this formula.
With the release of macOS Sierra the Apache module is now not built by default. If you want to build it on your system
you have to install php with the --with-apache option. See brew options php56 for more details.
To have launchd start homebrew/php/php56 now and restart at login:
brew services start homebrew/php/php56
To be honest, I'm not sure I follow it. Which bits do I need to do - not even sure i know where to find these directories if I'm honest
Yo Pete!
Yea, it can be a lot :). Here's what you should do:
Run php -v
from the command line. We want the version to be 5.6.XX, probably 5.6.27, but the last number doesn't really matter. If it is, yay! Your new PHP is being used. If it is still 5.5.36... then your old PHP from OSX is still being used. If you still have the old version, then do the following:
A) In your terminal, edit your ~/.profile
file. I use vim, so I say vim ~/.profile
. If you don't have this file, you can just create it
B) Anywhere inside, add this:
export PATH="$(brew --prefix homebrew/php/php56)/bin:$PATH"
Then open a new tab, and try php -v
again, it should use the correct, new version :).
Don't worry about the other stuff. Basically, PHP is an executable... but we just need to make sure that your terminal sees the new php executable, not the old one. Also, after you do all this, if you're using the built-in PHP web server like we do in this tutorial (using app/console server:run or bin/console server:run depending on your Symfony version), then stop that (ctrl+C), open a new tab, and restart it (so that it uses the new PHP).
Let me know if this works!
yo there thanks for the effort of the screencast, im a tad late but hey! im here! lol.
I have a question for you, regarding the Repository directory, in regards to structure, etc, why do you like it so? any specific reasons other than just "organization" of your code? or its there a deeper meaning to it?
Hey jlchafardet! Welcome - late, but still here ;).
About the "Repository" directory itself, I like this because the only other alternative that people use is to put their *Repository classes into the Entity directory (and then it's a mixture of entities and repositories). But, no deeper meaning :). If you're asking why I like organizing things into repository classes in general, it's because I *love* having 100% of my database queries in 1 spot - it makes future database changes and re-using query logic really easy.
Anyways - I hope I hit on your question. Cheers!
Yeah, i guessed as much, it makes sense, keeping things organized allow for better understanding and easier scalability.
cheers mate! thanks for taking the time to answer :D
Hi, thanks for this very usefull tutorial, action shortcut "alt+enter" for creating the repository (at 4min) seems very neat, unfortunately, it does nothing on my computer, is there a new shortcut for 2017.2? or an alternative way to access this menu (does this menu call "action menu" ? i can't find where it is) ?
Hey Gaétan Darquié
The shortcut key depends if you are on a mac or windows, you can see all available shortcuts (even create your custom ones) by going to settings->Keymap
Cheers!
hi,
Can i define associations across different entity managers ?
i have this error Doctrine2: Cross-Database Join Column throws Mapping-Exception
thanks
"Houston: no signs of life"
Start the conversation!
What PHP libraries does this tutorial use?
// composer.json
{
"require": {
"php": ">=5.3.3",
"symfony/symfony": "~2.4", // v2.4.2
"doctrine/orm": "~2.2,>=2.2.3", // v2.4.2
"doctrine/doctrine-bundle": "~1.2", // v1.2.0
"twig/extensions": "~1.0", // v1.0.1
"symfony/assetic-bundle": "~2.3", // v2.3.0
"symfony/swiftmailer-bundle": "~2.3", // v2.3.5
"symfony/monolog-bundle": "~2.4", // v2.5.0
"sensio/distribution-bundle": "~2.3", // v2.3.4
"sensio/framework-extra-bundle": "~3.0", // v3.0.0
"sensio/generator-bundle": "~2.3", // v2.3.4
"incenteev/composer-parameter-handler": "~2.0", // v2.1.0
"doctrine/doctrine-fixtures-bundle": "~2.2.0" // v2.2.0
}
}
Ryan i went ahead and installed mysql, which seemed to go fine (!)
However, now when going through the below part of the tutorial, I get no connection error, but the terminal just does nothing (left up to 10 mins):
$ php app/console doctrine:generate:entity
Welcome to the Doctrine2 entity generator
This command helps you generate Doctrine2 entities.
First, you need to give the entity name you want to generate.
You must use the shortcut notation like AcmeBlogBundle:Post.
The Entity shortcut name: EventBundle:Event
After that, nothing moves. If I do CTRL+C, my PHP web server shows:
[Mon Nov 14 12:30:14 2016] 127.0.0.1:55835 Invalid request (Unexpected EOF)
Any ideas?