如何在MAMP中访问PDO?

I'm setting up a PDO connection in a test script:

use app\SomeDAO;

class SomeTest extends \PHPUnit_Framework_TestCase
{
    protected $db;

    public function setUp()
    {
        $dsn = "mysql:host=localhost;dbname=baseball;user=root;password=root";
        $this->db = new PDO($dsn);
    }

I'm getting an error:

PDOException: SQLSTATE[HY000] [2002] No such file or directory.

How can I use PDO here?

In Unix based (like linux, bsd, or OS X) systems, with MySQL localhost is secret code for try-to-use-a-socket, unless a you force it via a protocol flag to not do this (and no one ever does this). Just remember localhost usually equals socket file.

If Mysql in your MAMP is running in non-socket mode, you can try replacing the host value with 127.0.0.1 which connects via TCP on via port to the local machine--you'll need to figure out which port it's running on if it's not the default port.

If you look at the MAMP start script

  less /Applications/MAMP/bin/startMysql.sh

You can see if it's starting in socket mode, and what file it's using if it has a config param like:

  --socket=/Applications/MAMP/tmp/mysql/mysql.sock 

You can also investigate what open socket mysql might be using by following the answer in this question: error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'

If you're running in socket mode, you need to make sure PDO knows the path to the socket file. One way to do this is specify the unix_socket instead of host in the dsn:

  $dsn =  "mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=baseball;user=root;password=root";