Solucionado (ver solução)
Solucionado
(ver solução)
6
respostas

Docker com PHP e Doctrine

Olá pessoal. Estou desenvolvendo uma aplicação que simula entrada de pacientes em um hospital.

Na parte do Servidor, decidi usar Slim Framework PHP e Doctrine para fazer a persistência, entretanto estou tendo problema em fazer conexão com banco de dados e gerar as tabelas

Erro ao executar vendor/bin/doctrine orm:schema-tool:create no terminal

In AbstractMySQLDriver.php line 115:
  An exception occured in driver: could not find driver

In PDOConnection.php line 47:
  could not find driver

In PDOConnection.php line 43:
  could not find driver

Meu Bootstrap.php:

<?php
// bootstrap.php
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;

require_once "vendor/autoload.php";

// Create a simple "default" Doctrine ORM configuration for Annotations
$isDevMode = true;
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src/HospitalApi/Entity"), $isDevMode);
// or if you prefer XML
//$config = Setup::createXMLMetadataConfiguration(array(__DIR__."/config"), $isDevMode);

// database configuration parameters
$conn = array(
    'dbname' => 'hospital_api',
    'user' => 'root',
    'password' => '',
    'host' => 'mysql',
    'driver' => 'pdo_mysql',
    // 'path' => __DIR__ . 'db.sqlite',
);

// obtaining the entity manager
$entityManager = EntityManager::create($conn, $config);

E as entidades da usuário com as notações: Caminho para entidades: /server/src/HospitalApi/Entity/Usuario.php

 /**
     * @Entity
     * @Table(name="usuario")
     */
    class Usuario{

        /**
         * @var integer @Id
         *      @Column(name="id", type="integer")
         *      @GenerateValue(strategy="AUTO")
         */
        private $id;

        /**
         * @var string @Column(type="string", length=255)*/
        private $email;

        /**
         * @var string @Column(type="string", length=255)*/
        private $senha;

        /**
         * @var string @Column(type="string", length=255)*/
        private $endereco;

Se precisar meu git com projeto completo https://github.com/GustavoFSoares/hospital

De todo modo, value a força

6 respostas

Oi Gustavo, tudo bem? Me parece que o seu PHP está faltando a extensão do pdo-mysql. Isso por que a PDO usa drivers para conectar com cada banco. Verifica se é isso mesmo. Talvez seja por que o driver está desabilitado no php.ini

Eai.

Concordo. pdo-mysql não ta lá, apenas pdo-sqlite.

https://ibb.co/ns67Zc

Mas máquina Docker não tem php.ini

root@2b36e79596d7:/var/www# find / -name php.ini
/var/www/vendor/doctrine/cache/tests/travis/php.ini

Tentei copiar o php.ini do meu computador cliente, mas não teve alteração.


Docker-compose

    slim_1:
        image: php
        container_name: slim_1
        working_dir: /var/www
        command: php -S 0.0.0.0:8080 -t /var/www/public public/index.php
        environment:
            docker: "true"
        ports:
            - 3001:8080
        networks:
            hospital-network:
                ipv4_address: 172.19.0.7
        depends_on:
            - mysql
        volumes:
            - ./server:/var/www
            - ./server/logs:/var/www/logs
            - /etc/php/7.0/cli/php.ini:/usr/local/etc/php/php.ini

Alguma ideia?

Consegui copiar meu php.ini para dentro do container, mas não alterou phpinfo()

Configuration File (php.ini) Path    /usr/local/etc/php

Ideias? Abaixo tem uma parte do php.ini que estou usando

[PHP]
;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;

; If you wish to have an extension loaded automatically, use the following
; syntax:
;
;   extension=modulename.extension
;
; For example, on Windows:
;
;   extension=msql.dll
;
; ... or under UNIX:
;
;   extension=msql.so
;
; ... or with a path:
;
;   extension=/path/to/extension/msql.so
;
; If you only provide the name of the extension, PHP will look for it in its
; default extension directory.
;
; Windows Extensions
; Note that ODBC support is built in, so no dll is needed for it.
; Note that many DLL files are located in the extensions/ (PHP 4) ext/ (PHP 5+)
; extension folders as well as the separate PECL DLL download (PHP 5+).
; Be sure to appropriately set the extension_dir directive.
;
;extension=php_bz2.dll
;extension=php_curl.dll
;extension=php_fileinfo.dll
;extension=php_ftp.dll
;extension=php_gd2.dll
;extension=php_gettext.dll
;extension=php_gmp.dll
;extension=php_intl.dll
;extension=php_imap.dll
;extension=php_interbase.dll
;extension=php_ldap.dll
;extension=php_mbstring.dll
;extension=php_exif.dll      ; Must be after mbstring as it depends on it
;extension=php_mysqli.dll
;extension=php_oci8_12c.dll  ; Use with Oracle Database 12c Instant Client
;extension=php_openssl.dll
;extension=php_pdo_firebird.dll
extension=php_pdo_mysql.dll
;extension=php_pdo_oci.dll
;extension=php_pdo_odbc.dll
;extension=php_pdo_pgsql.dll
;extension=php_pdo_sqlite.dll
;extension=php_pgsql.dll
;extension=php_shmop.dll

; The MIBS data available in the PHP distribution must be installed.
; See http://www.php.net/manual/en/snmp.installation.php
;extension=php_snmp.dll

;extension=php_soap.dll
;extension=php_sockets.dll
;extension=php_sqlite3.dll
;extension=php_tidy.dll
;extension=php_xmlrpc.dll
;extension=php_xsl.dll

;;;;;;;;;;;;;;;;;;;
; Module Settings ;
;;;;;;;;;;;;;;;;;;;

[CLI Server]
; Whether the CLI web server uses ANSI color coding in its terminal output.
cli_server.color = On

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
;date.timezone =

; http://php.net/date.default-latitude
;date.default_latitude = 31.7667

; http://php.net/date.default-longitude
;date.default_longitude = 35.2333

; http://php.net/date.sunrise-zenith
;date.sunrise_zenith = 90.583333

; http://php.net/date.sunset-zenith
;date.sunset_zenith = 90.583333

[filter]
; http://php.net/filter.default
;filter.default = unsafe_raw

; http://php.net/filter.default-flags
;filter.default_flags =

[intl]
;intl.default_locale =
; This directive allows you to produce PHP errors when some error
; happens within intl functions. The value is the level of the error produced.
; Default is 0, which does not produce any errors.
;intl.error_level = E_WARNING
;intl.use_exceptions = 0

[sqlite3]
;sqlite3.extension_dir =

[Pcre]
;PCRE library backtracking limit.
; http://php.net/pcre.backtrack-limit
;pcre.backtrack_limit=100000

;PCRE library recursion limit.
;Please note that if you set this value to a high number you may consume all
;the available process stack and eventually crash PHP (due to reaching the
;stack size limit imposed by the Operating System).
; http://php.net/pcre.recursion-limit
;pcre.recursion_limit=100000

;Enables or disables JIT compilation of patterns. This requires the PCRE
;library to be compiled with JIT support.
;pcre.jit=1

[Pdo]
; Whether to pool ODBC connections. Can be one of "strict", "relaxed" or "off"
; http://php.net/pdo-odbc.connection-pooling
pdo_odbc.connection_pooling=strict

;pdo_odbc.db2_instance_name

[Pdo_mysql]
; If mysqlnd is used: Number of cache slots for the internal result set cache
; http://php.net/pdo_mysql.cache_size
pdo_mysql.cache_size = 2000

; Default socket name for local MySQL connects.  If empty, uses the built-in
; MySQL defaults.
; http://php.net/pdo_mysql.default-socket
pdo_mysql.default_socket=
solução!

Opa Gustavo, o problema diz que o driver não foi encontrado, não é só questão de mudar o php.ini, você realmente precisa instalar a extensão. Como você instala o PHP no Docker? O mesmo vale pras extensões do PHP, como como apt-get install pdo-mysql. Pegou a ideia?

Boa Cara. Detalhe só que não instala com apt-get, ao menos no meu container.

Eu instalei com docker-php-ext-install pdo pdo_mysql, mas depois dei um php -i|grep PDO pra ver e estava lá. Valeeu muito a força!

Boa! Eu só falei apt-get por que queria dar uma dica, não sei bem como funciona no docker, mas no vagrant era exatamente assim que faria. hahah, vou estudar esse tal de docker depois.

Valeu Gustavo!

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software