One place for hosting & domains

      How To Install PHP 7.4 and Set Up a Local Development Environment on Ubuntu 18.04


      The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.

      Introduction

      PHP is a popular server scripting language known for creating dynamic and interactive web pages. Getting up and running with your language of choice is the first step in learning to program.

      This tutorial will guide you through installing PHP 7.4 on Ubuntu and setting up a local programming environment via the command line. You will also install a dependency manager, Composer, and test your installation by running a script.

      Prerequisites

      To complete this tutorial, you will need a local or virtual machine with Ubuntu 18.04 installed and have administrative access and an internet connection to that machine. You can download this operating system via the Ubuntu releases page.

      Step 1 — Setting Up PHP 7.4

      You’ll be completing your installation and setup on the command line, which is a non-graphical way to interact with your computer. That is, instead of clicking on buttons, you’ll be typing in text and receiving feedback from your computer through text as well.

      The command line, also known as a shell or terminal, can help you modify and automate many of the tasks you do on a computer every day and is an essential tool for software developers. There are many terminal commands to learn that can enable you to do more powerful things. The article An Introduction to the Linux Terminal can get you better oriented with the terminal.

      On Ubuntu, you can find the Terminal application by clicking on the Ubuntu icon in the upper-left-hand corner of your screen and typing terminal into the search bar. Click on the Terminal application icon to open it. Alternatively, you can hit the CTRL, ALT, and T keys on your keyboard at the same time to open the Terminal application automatically.

      Ubuntu terminal

      You will want to avoid relying on the default version of PHP because that default version could change depending on where you are running your code. You may also wish to install a different version to match an application you are using or to upgrade to a newer version, such as PHP 8.

      Run the following command to update apt-get itself, which ensures that you have access to the latest versions of anything you want to install:

      Next, install software-properties-common, which adds management for additional software sources:

      • sudo apt -y install software-properties-common

      The -y flag will automatically agree to the installation. Without that, you would receive a prompt in your terminal window for each installation.

      Next, install the repository ppa:ondrej/php, which will give you all your versions of PHP:

      • sudo add-apt-repository ppa:ondrej/php

      Finally, you update apt-get again so your package manager can see the newly listed packages:

      Now you’re ready to install PHP 7.4 using the following command:

      • sudo apt -y install php7.4

      Check the version installed:

      You will receive something similar to the following:

      Output

      PHP 7.4.0beta4 (cli) (built: Aug 28 2019 11:41:49) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0-dev, Copyright (c) Zend Technologies with Zend OPcache v7.4.0beta4, Copyright (c), by Zend Technologies

      Besides PHP itself, you will likely want to install some additional PHP modules. You can use this command to install additional modules, replacing PACKAGE_NAME with the package you wish to install:

      • sudo apt-get install php7.4-PACKAGE_NAME

      You can also install more than one package at a time. Here are a few suggestions of the most common modules you will most likely want to install:

      • sudo apt-get install -y php7.4-cli php7.4-json php7.4-common php7.4-mysql php7.4-zip php7.4-gd php7.4-mbstring php7.4-curl php7.4-xml php7.4-bcmath

      This command will install the following modules:

      • php7.4-cli - command interpreter, useful for testing PHP scripts from a shell or performing general shell scripting tasks
      • php7.4-json - for working with JSON data
      • php7.4-common - documentation, examples, and common modules for PHP
      • php7.4-mysql - for working with MySQL databases
      • php7.4-zip - for working with compressed files
      • php7.4-gd - for working with images
      • php7.4-mbstring - used to manage non-ASCII strings
      • php7.4-curl - lets you make HTTP requests in PHP
      • php7.4-xml - for working with XML data
      • php7.4-bcmath - used when working with precision floats

      PHP configurations related to Apache are stored in /etc/php/7.4/apache2/php.ini. You can list all loaded PHP modules with the following command:

      You have installed PHP and verified the version you have running. You also installed any required PHP modules and were able to list the modules that you have loaded.

      You could start using PHP right now, but you will likely want to use various libraries to build PHP applications quickly. Before you test your PHP environment, first set up a dependency manager for your projects.

      Step 2 — Setting Up Composer for Dependency Management (Optional)

      Libraries are a collection of code that can help you solve common problems without needing to write everything yourself. Since there are many libraries available, using a dependency manager will help you manage multiple libraries as you become more experienced in writing PHP.

      Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and will manage installing and updating these packages.

      Although similar, Composer is not a package manager in the same sense as yum or apt. It deals with “packages” or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default, it does not install anything globally. Thus, it is a dependency manager. It does, however, support a global project for convenience via the global command.

      This idea is not new, and Composer is strongly inspired by Node’s npm and Ruby’s bundler.

      Suppose:

      • You have a project that depends on several libraries.
      • Some of those libraries depend on other libraries.

      Composer:

      • Enables you to declare the libraries you depend on.
      • Finds out which versions of which packages can and need to be installed and installs them by downloading them into your project.
      • Enables you to update all your dependencies in one command.
      • Enables you to see the Basic Usage chapter for more details on declaring dependencies.

      There are, in short, two ways to install Composer: locally as part of your project or globally as a system-wide executable. Either way, you will start with the local install.

      Locally

      To quickly install Composer in the current directory, run this script in your terminal:

      • php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
      • php -r "if (hash_file('sha384', 'composer-setup.php') === '756890a4488ce9024fc62c56153228907f1545c228516cbf63f885e036d37e9a59d27d63f46af1d4d07ee0f76181c7d3') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
      • php composer-setup.php
      • php -r "unlink('composer-setup.php');"

      This installer script will check some php.ini settings, warn you if they are set incorrectly, and then download the latest composer.phar in the current directory. The four lines will, in order:

      • Download the installer to the current directory
      • Verify the installer SHA-384, which you can also cross-check here
      • Run the installer
      • Remove the installer

      The installer will check a few PHP settings and then download composer.phar to your working directory. This file is the Composer binary. It is a PHAR (PHP archive), which is an archive format for PHP that can be run on the command line, amongst other things.

      In order to run Composer, you use php composer.phar. As an example, run this command to see the version of Composer you have installed:

      • php composer.phar --version

      To use Composer locally, you will want your composer.phar file to be in your project’s root directory. You can start in your project directory before installing Composer. You can also move the file after installation. You can also install Composer to a specific directory by using the --install-dir option and additionally (re)name it using the --filename option.

      Since Composer is something used across projects, it’s recommended that you continue to the next portion and set Composer to run globally.

      Globally

      You can place the Composer PHAR anywhere you wish. If you put it in a directory that is part of your $PATH, you can access it globally. You can even make it executable on Ubuntu (and other Unix systems) and invoke it without directly using the PHP interpreter.

      After installing locally, run this command to move composer.phar to a directory that is in your path:

      • sudo mv composer.phar /usr/local/bin/composer

      If you’d like to install it only for your user and avoid requiring root permissions, you can use ~/.local/bin instead, which is available by default on some Linux distributions:

      • mv composer.phar ~/.local/bin/composer

      Now to run Composer, use composer instead of php composer.phar. To check for your Composer version, run:

      As a final step, you may optionally initialize your project with composer init. This will create the composer.json file that will manage your project dependencies. Initializing the project will also let you define project details such as Author and License, and use Composer’s autoload functionality. You can define dependencies now or add them later.

      Run this command to initialize a project:

      Running this command will start the setup wizard. Details that you enter in the wizard can be updated later, so feel free to leave the defaults and just press ENTER. If you aren’t ready to install any dependencies, you can choose no. Enter in your details at each prompt:

      Output

      This command will guide you through creating your composer.json config. Package name (sammy/php_install): sammy/project1 Description []: Author [Sammy <sammy@digitalocean.com>, n to skip]: Minimum Stability []: Package Type (e.g. library, project, metapackage, composer-plugin) []: project License []: Define your dependencies. Would you like to define your dependencies (require) interactively [yes]? no Would you like to define your dev dependencies (require-dev) interactively [yes]? no { "name": "sammy/project1", "type": "project", "authors": [ { "name": "Sammy", "email": "sammy@digitalocean.com" } ], "require": {} } Do you confirm generation [yes]? yes

      Before you confirm the generation, you will see a sample of the composer.json file that the wizard will create. If it all looks good, you can confirm the default of yes. If you need to start over, choose no.

      The first time you define any dependency, Composer will create a vendor folder. All dependencies install into this vendor folder. Composer also creates a composer.lock file. This file specifies the exact version of each dependency and subdependency used in your project. This assures that any machine on which your program is run, will be using the exact same version of each packages.

      Note: The vendor folder should never be committed to your version control system (VCS). The vendor folder only contains packages you have installed from other vendors. Those individual vendors will maintain their own code in their own version control systems. You should only be tracking the code you write. Instead of committing the vendor folder, you only need to commit your composer.json and composer.lock files. You can learn more about ignoring specific files in How To Use Git: A Reference Guide.

      Now that you have PHP installed and a way to manage your project dependencies using Composer, you’re ready to test your environment.

      Step 3 — Testing the PHP Environment

      To test that your system is configured correctly for PHP, you can create and run a basic PHP script. Call this script hello.php:

      This will open a blank file. Put the following text, which is valid PHP code, inside the file:

      hello.php

      <?php
      echo 'Hello World!';
      ?>
      

      Once you’ve added the text, save and close the file. You can do this by holding down the CTRL key and pressing the x key. Then choose y and press ENTER.

      Now you can test to make sure that PHP processes your script correctly. Type php to tell PHP to process the file, followed by the name of the file:

      If the PHP is processed properly, you will see only the characters within the quotes:

      Output

      Hello World!

      PHP has successfully processed the script, meaning that your PHP environment is successfully installed and you’re ready to continue your programming journey.

      Conclusion

      At this point, you have a PHP 7.4 programming environment set up on your local Ubuntu machine and can begin a coding project.

      Before you start coding, you may want to set up an Integrated Development Environment (IDE). While there are many IDEs to choose from, VS Code is a popular choice as it offers many powerful features such as a graphical interface, syntax highlighting, and debugging.

      With your local machine ready for software development, you can continue to learn more about coding in PHP by following How To Work With Strings in PHP.



      Source link

      How To Install PHP 7.4 and Set Up a Local Development Environment on Ubuntu 20.04


      The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.

      Introduction

      PHP is a popular server scripting language known for creating dynamic and interactive web pages. Getting up and running with your language of choice is the first step in learning to program.

      This tutorial will guide you through installing PHP 7.4 on Ubuntu and setting up a local programming environment via the command line. You will also install a dependency manager, Composer, and test your installation by running a script.

      Prerequisites

      To complete this tutorial, you will need a local or virtual machine with Ubuntu 20.04 installed and have administrative access and an internet connection to that machine. You can download this operating system via the Ubuntu releases page.

      Step 1 — Setting Up PHP 7.4

      You’ll be completing your installation and setup on the command line, which is a non-graphical way to interact with your computer. That is, instead of clicking on buttons, you’ll be typing in text and receiving feedback from your computer through text as well.

      The command line, also known as a shell or terminal, can help you modify and automate many of the tasks you do on a computer every day and is an essential tool for software developers. There are many terminal commands to learn that can enable you to do more powerful things. The article An Introduction to the Linux Terminal can get you better oriented with the terminal.

      On Ubuntu, you can find the Terminal application by clicking on the Ubuntu icon in the upper-left-hand corner of your screen and typing terminal into the search bar. Click on the Terminal application icon to open it. Alternatively, you can hit the CTRL, ALT, and T keys on your keyboard at the same time to open the Terminal application automatically.

      Ubuntu terminal

      Note: Ubuntu 20.04 ships with PHP 7.4 in its upstream repositories. This means that if you attempt to install PHP without a specified version, it will use 7.4.

      You will want to avoid relying on the default version of PHP because that default version could change depending on where you are running your code. You may also wish to install a different version to match an application you are using or to upgrade to a newer version, such as PHP 8.

      Run the following command to update apt-get itself, which ensures that you have access to the latest versions of anything you want to install:

      Next, install software-properties-common, which adds management for additional software sources:

      • sudo apt -y install software-properties-common

      The -y flag will automatically agree to the installation. Without that, you would receive a prompt in your terminal window for each installation.

      Next, install the repository ppa:ondrej/php, which will give you all your versions of PHP:

      • sudo add-apt-repository ppa:ondrej/php

      Finally, you update apt-get again so your package manager can see the newly listed packages:

      Now you’re ready to install PHP 7.4 using the following command:

      • sudo apt -y install php7.4

      Check the version installed:

      You will receive something similar to the following:

      Output

      PHP 7.4.0beta4 (cli) (built: Aug 28 2019 11:41:49) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0-dev, Copyright (c) Zend Technologies with Zend OPcache v7.4.0beta4, Copyright (c), by Zend Technologies

      Besides PHP itself, you will likely want to install some additional PHP modules. You can use this command to install additional modules, replacing PACKAGE_NAME with the package you wish to install:

      • sudo apt-get install php7.4-PACKAGE_NAME

      You can also install more than one package at a time. Here are a few suggestions of the most common modules you will most likely want to install:

      • sudo apt-get install -y php7.4-cli php7.4-json php7.4-common php7.4-mysql php7.4-zip php7.4-gd php7.4-mbstring php7.4-curl php7.4-xml php7.4-bcmath

      This command will install the following modules:

      • php7.4-cli - command interpreter, useful for testing PHP scripts from a shell or performing general shell scripting tasks
      • php7.4-json - for working with JSON data
      • php7.4-common - documentation, examples, and common modules for PHP
      • php7.4-mysql - for working with MySQL databases
      • php7.4-zip - for working with compressed files
      • php7.4-gd - for working with images
      • php7.4-mbstring - used to manage non-ASCII strings
      • php7.4-curl - lets you make HTTP requests in PHP
      • php7.4-xml - for working with XML data
      • php7.4-bcmath - used when working with precision floats

      PHP configurations related to Apache are stored in /etc/php/7.4/apache2/php.ini. You can list all loaded PHP modules with the following command:

      You have installed PHP and verified the version you have running. You also installed any required PHP modules and were able to list the modules that you have loaded.

      You could start using PHP right now, but you will likely want to use various libraries to build PHP applications quickly. Before you test your PHP environment, first set up a dependency manager for your projects.

      Step 2 — Setting Up Composer for Dependency Management (Optional)

      Libraries are a collection of code that can help you solve common problems without needing to write everything yourself. Since there are many libraries available, using a dependency manager will help you manage multiple libraries as you become more experienced in writing PHP.

      Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and will manage installing and updating these packages.

      Although similar, Composer is not a package manager in the same sense as yum or apt. It deals with “packages” or libraries, but it manages them on a per-project basis, installing them in a directory (e.g. vendor) inside your project. By default, it does not install anything globally. Thus, it is a dependency manager. It does, however, support a global project for convenience via the global command.

      This idea is not new, and Composer is strongly inspired by Node’s npm and Ruby’s bundler.

      Suppose:

      • You have a project that depends on several libraries.
      • Some of those libraries depend on other libraries.

      Composer:

      • Enables you to declare the libraries you depend on.
      • Finds out which versions of which packages can and need to be installed and installs them by downloading them into your project.
      • Enables you to update all your dependencies in one command.
      • Enables you to see the Basic Usage chapter for more details on declaring dependencies.

      There are, in short, two ways to install Composer: locally as part of your project or globally as a system-wide executable. Either way, you will start with the local install.

      Locally

      To quickly install Composer in the current directory, run this script in your terminal:

      • php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
      • php -r "if (hash_file('sha384', 'composer-setup.php') === '756890a4488ce9024fc62c56153228907f1545c228516cbf63f885e036d37e9a59d27d63f46af1d4d07ee0f76181c7d3') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
      • php composer-setup.php
      • php -r "unlink('composer-setup.php');"

      This installer script will check some php.ini settings, warn you if they are set incorrectly, and then download the latest composer.phar in the current directory. The four lines will, in order:

      • Download the installer to the current directory
      • Verify the installer SHA-384, which you can also cross-check here
      • Run the installer
      • Remove the installer

      The installer will check a few PHP settings and then download composer.phar to your working directory. This file is the Composer binary. It is a PHAR (PHP archive), which is an archive format for PHP that can be run on the command line, amongst other things.

      In order to run Composer, you use php composer.phar. As an example, run this command to see the version of Composer you have installed:

      • php composer.phar --version

      To use Composer locally, you will want your composer.phar file to be in your project’s root directory. You can start in your project directory before installing Composer. You can also move the file after installation. You can also install Composer to a specific directory by using the --install-dir option and additionally (re)name it using the --filename option.

      Since Composer is something used across projects, it’s recommended that you continue to the next portion and set Composer to run globally.

      Globally

      You can place the Composer PHAR anywhere you wish. If you put it in a directory that is part of your $PATH, you can access it globally. You can even make it executable on Ubuntu (and other Unix systems) and invoke it without directly using the PHP interpreter.

      After installing locally, run this command to move composer.phar to a directory that is in your path:

      • sudo mv composer.phar /usr/local/bin/composer

      If you’d like to install it only for your user and avoid requiring root permissions, you can use ~/.local/bin instead, which is available by default on some Linux distributions:

      • mv composer.phar ~/.local/bin/composer

      Now to run Composer, use composer instead of php composer.phar. To check for your Composer version, run:

      As a final step, you may optionally initialize your project with composer init. This will create the composer.json file that will manage your project dependencies. Initializing the project will also let you define project details such as Author and License, and use Composer’s autoload functionality. You can define dependencies now or add them later.

      Run this command to initialize a project:

      Running this command will start the setup wizard. Details that you enter in the wizard can be updated later, so feel free to leave the defaults and just press ENTER. If you aren’t ready to install any dependencies, you can choose no. Enter in your details at each prompt:

      Output

      This command will guide you through creating your composer.json config. Package name (sammy/php_install): sammy/project1 Description []: Author [Sammy <sammy@digitalocean.com>, n to skip]: Minimum Stability []: Package Type (e.g. library, project, metapackage, composer-plugin) []: project License []: Define your dependencies. Would you like to define your dependencies (require) interactively [yes]? no Would you like to define your dev dependencies (require-dev) interactively [yes]? no { "name": "sammy/project1", "type": "project", "authors": [ { "name": "Sammy", "email": "sammy@digitalocean.com" } ], "require": {} } Do you confirm generation [yes]? yes

      Before you confirm the generation, you will see a sample of the composer.json file that the wizard will create. If it all looks good, you can confirm the default of yes. If you need to start over, choose no.

      The first time you define any dependency, Composer will create a vendor folder. All dependencies install into this vendor folder. Composer also creates a composer.lock file. This file specifies the exact version of each dependency and subdependency used in your project. This assures that any machine on which your program is run, will be using the exact same version of each packages.

      Note: The vendor folder should never be committed to your version control system (VCS). The vendor folder only contains packages you have installed from other vendors. Those individual vendors will maintain their own code in their own version control systems. You should only be tracking the code you write. Instead of committing the vendor folder, you only need to commit your composer.json and composer.lock files. You can learn more about ignoring specific files in How To Use Git: A Reference Guide.

      Now that you have PHP installed and a way to manage your project dependencies using Composer, you’re ready to test your environment.

      Step 3 — Testing the PHP Environment

      To test that your system is configured correctly for PHP, you can create and run a basic PHP script. Call this script hello.php:

      This will open a blank file. Put the following text, which is valid PHP code, inside the file:

      hello.php

      <?php
      echo 'Hello World!';
      ?>
      

      Once you’ve added the text, save and close the file. You can do this by holding down the CTRL key and pressing the x key. Then choose y and press ENTER.

      Now you can test to make sure that PHP processes your script correctly. Type php to tell PHP to process the file, followed by the name of the file:

      If the PHP is processed properly, you will see only the characters within the quotes:

      Output

      Hello World!

      PHP has successfully processed the script, meaning that your PHP environment is successfully installed and you’re ready to continue your programming journey.

      Conclusion

      At this point, you have a PHP 7.4 programming environment set up on your local Ubuntu machine and can begin a coding project.

      Before you start coding, you may want to set up an Integrated Development Environment (IDE). While there are many IDEs to choose from, VS Code is a popular choice as it offers many powerful features such as a graphical interface, syntax highlighting, and debugging.

      With your local machine ready for software development, you can continue to learn more about coding in PHP by following How To Work With Strings in PHP.



      Source link

      Cómo desarrollar un sitio web Drupal 9 en su equipo local usando Docker y DDEV


      El autor seleccionó la organización Diversity in Tech Fund para que reciba una donación como parte del programa Write for DOnations.

      Introducción

      DDEV es un herramienta de código abierto que utiliza Docker para crear entornos de desarrollo locales para muchos marcos PHP diferentes. Con el poder de la creación de contenedores, DDEV puede simplificar de forma significativa la forma en que trabaja en múltiples proyectos que utilizan múltiples pilas tecnológicas y múltiples servidores en la nube. DDEV incluye plantillas para WordPress, Laravel, Magento, TYPO3, Drupal y mucho más.

      Drupal 9 fue lanzado el 3 de junio del 2020 para la CMS Drupal. Conocido por su facilidad de uso y una enorme biblioteca de módulos y temas, Drupal es un marco PHP popular para crear y mantener varios sitios web y aplicaciones de todos los tamaños.

      En este tutorial, comenzará a desarrollar un sitio web Drupal 9 en su equipo local usando DDEV. Esto le permitirá crear su sitio web primero y, más tarde, cuando esté listo, implementar su proyecto en un servidor de producción.

      Requisitos previos

      Para completar este tutorial, necesitará lo siguiente:

      Nota: Es posible desarrollar Drupal 9 usando DDEV en un servidor remoto, pero necesitará una solución para acceder a localhost en un navegador web. El comando DDEV, ddev share funciona con ngrok, que crea un túnel seguro en su servidor para que usted y otras partes interesadas vean su sitio en desarrollo. Para uso personal, también podría instalar una GUI en su servidor remoto y acceder a su sitio en desarrollo a través de un navegador web dentro de esa interfaz. Para hacer esto, podría seguir nuestra guía sobre Cómo instalar y configurar VNC en Ubuntu 20.04. Para una solución de GUI aún más rápida, puede seguir nuestra guía sobre cómo configurar un escritorio remoto con X2Go en Ubuntu 20.04.

      Paso 1: Instalar DDEV

      En este paso instalará DDEV en su equipo local. La Opción 1 incluye instrucciones para macOS mientras que la Opción 2 proporciona instrucciones para Linux. Este tutorial se probó en DDEV versión 1.15.0.

      Opción 1: Instalar DDEV en macOS

      DDEV aconseja que los usuarios de macOS instalen su herramienta usando el administrador de paquetes Homebrew. Utilice el siguiente comando brew para instalar la versión estable más reciente:

      • brew tap drud/ddev && brew install drud/ddev/ddev

      Si prefiere la versión absolutamente más reciente, puede usar brew para instalar ddev-edge:

      • brew tap drud/ddev-edge && brew install drud/ddev-edge/ddev

      Si ya tiene una versión de DDEV instalada, o si alguna vez desea actualizar su versión, cierre DDEV y utilice brew para actualizar su instalación:

      • ddev poweroff
      • brew upgrade ddev

      Una vez que haya instalado o actualizado DDEV, ejecute ddev version para verificar su software:

      Verá un resultado similar a este:

      Output

      DDEV-Local version v1.15.0 commit v1.15.0 db drud/ddev-dbserver-mariadb-10.2:v1.15.0 dba phpmyadmin/phpmyadmin:5 ddev-ssh-agent drud/ddev-ssh-agent:v1.15.0 docker 19.03.8 docker-compose 1.25.5 os darwin router drud/ddev-router:v1.15.0 web drud/ddev-webserver:v1.15.0

      DDEV incluye una potente CLI o interfaz de línea de comandos. Ejecute ddev para obtener más información sobre algunos comandos comunes:

      Verá lo siguiente:

      Output

      Create and maintain a local web development environment. Docs: https://ddev.readthedocs.io Support: https://ddev.readthedocs.io/en/stable/#support Usage: ddev [command] Available Commands: auth A collection of authentication commands composer Executes a composer command within the web container config Create or modify a ddev project configuration in the current directory debug A collection of debugging commands delete Remove all project information (including database) for an existing project describe Get a detailed description of a running ddev project. exec Execute a shell command in the container for a service. Uses the web service by default. export-db Dump a database to a file or to stdout help Help about any command hostname Manage your hostfile entries. import-db Import a sql file into the project. import-files Pull the uploaded files directory of an existing project to the default public upload directory of your project. list List projects logs Get the logs from your running services. pause uses 'docker stop' to pause/stop the containers belonging to a project. poweroff Completely stop all projects and containers pull Pull files and database using a configured provider plugin. restart Restart a project or several projects. restore-snapshot Restore a project's database to the provided snapshot version. sequelpro This command is not available since sequel pro.app is not installed share Share project on the internet via ngrok. snapshot Create a database snapshot for one or more projects. ssh Starts a shell session in the container for a service. Uses web service by default. start Start a ddev project. stop Stop and remove the containers of a project. Does not lose or harm anything unless you add --remove-data. version print ddev version and component versions Flags: -h, --help help for ddev -j, --json-output If true, user-oriented output will be in JSON format. -v, --version version for ddev Use "ddev [command] --help" for more information about a command.

      Para obtener más información sobre cómo usar la CLI de DDEV, visite la documentación oficial de DDEV.

      Con DDEV instalado en su equipo local, ahora está listo para instalar Drupal 9 y comenzar a desarrollar un sitio web.

      Opción 2: Instalar DDEV en Linux

      En un sistema operativo Linux, puede instalar DDEV usando Homebrew para Linux o usando la secuencia de comandos de instalación oficial. En Ubuntu, comience actualizando su lista de paquetes en el administrador de paquetes apt (puede usar apt en Debian, de lo contrario utilice el administrador de paquetes equivalente asociado con su distribución Linux):

      Ahora instale algunos paquetes previos desde el repositorio oficial de Ubuntu:

      • sudo apt install build-essential apt-transport-https ca-certificates software-properties-common curl

      Estos paquetes le permitirán descargar la secuencia de comandos de instalación de DDEV desde su repositorio oficial GitHub.

      Ahora descargue la secuencia de comandos:

      • curl -O https://raw.githubusercontent.com/drud/ddev/master/scripts/install_ddev.sh

      Antes de ejecutar la secuencia de comandos, ábrala en nano o en su editor de texto preferido e inspeccione su contenido:

      nano install_ddev.sh
      

      Una vez que haya revisado el contenido de la secuencia de comandos y esté satisfecho, guarde y cierre el archivo. Ahora está listo para ejecutar la secuencia de comandos de instalación.

      Utilice el comando chmod para hacer que la secuencia de comandos sea ejecutable:

      Ahora ejecute la secuencia de comandos:

      Es posible que el proceso de instalación le pida que confirme algunos ajustes o que introduzca su contraseña sudo. Una vez completada la instalación, tendrá DDEV disponible en su sistema operativo Linux.

      Ejecute ddev version para verificar su software:

      Verá un resultado similar a este:

      Output

      DDEV-Local version v1.15.0 commit v1.15.0 db drud/ddev-dbserver-mariadb-10.2:v1.15.0 dba phpmyadmin/phpmyadmin:5 ddev-ssh-agent drud/ddev-ssh-agent:v1.15.0 docker 19.03.8 docker-compose 1.25.5 os linux router drud/ddev-router:v1.15.0 web drud/ddev-webserver:v1.15.0

      DDEV incluye una potente CLI o interfaz de línea de comandos. Ejecute ddev sin nada más para aprender sobre estos comandos comunes:

      Verá lo siguiente:

      Output

      Create and maintain a local web development environment. Docs: https://ddev.readthedocs.io Support: https://ddev.readthedocs.io/en/stable/#support Usage: ddev [command] Available Commands: auth A collection of authentication commands composer Executes a composer command within the web container config Create or modify a ddev project configuration in the current directory debug A collection of debugging commands delete Remove all project information (including database) for an existing project describe Get a detailed description of a running ddev project. exec Execute a shell command in the container for a service. Uses the web service by default. export-db Dump a database to a file or to stdout help Help about any command hostname Manage your hostfile entries. import-db Import a sql file into the project. import-files Pull the uploaded files directory of an existing project to the default public upload directory of your project. list List projects logs Get the logs from your running services. pause uses 'docker stop' to pause/stop the containers belonging to a project. poweroff Completely stop all projects and containers pull Pull files and database using a configured provider plugin. restart Restart a project or several projects. restore-snapshot Restore a project's database to the provided snapshot version. sequelpro This command is not available since sequel pro.app is not installed share Share project on the internet via ngrok. snapshot Create a database snapshot for one or more projects. ssh Starts a shell session in the container for a service. Uses web service by default. start Start a ddev project. stop Stop and remove the containers of a project. Does not lose or harm anything unless you add --remove-data. version print ddev version and component versions Flags: -h, --help help for ddev -j, --json-output If true, user-oriented output will be in JSON format. -v, --version version for ddev Use "ddev [command] --help" for more information about a command.

      Para obtener más información sobre cómo usar la CLI de DDEV, visite la documentación oficial de DDEV.

      Con DDEV instalado en su equipo local, ahora está listo para instalar Drupal 9 y comenzar a desarrollar un sitio web.

      Paso 2: Implementar un nuevo sitio Drupal 9 usando DDEV

      Con DDEV en ejecución, ahora lo usara para crear un sistema de archivos Drupal específico, instalar Drupal 9 e iniciar un proyecto de sitio web estándar.

      Primero, creará un directorio raíz del proyecto y luego entrará en él. Ejecutará todos los comandos restantes desde esta ubicación. Este tutorial usará d9test, pero puede llamar a su directorio de cualquier otra manera. Observe, sin embargo, que DDEV no gestiona bien los nombres con guion. Se considera una buena práctica evitar nombres de directorio como my-project o drupal-site-1.

      Cree el directorio raíz de su proyecto y entre en él:

      DDEV sobresale a la hora de crear árboles de directorio que coinciden con plataformas CMS específicas. Utilice el comando ddev config para crear una estructura de directorio específica para Drupal 9:

      • ddev config --project-type=drupal9 --docroot=web --create-docroot

      Verá un resultado similar a este:

      Output

      Creating a new ddev project config in the current directory (/Users/sammy/d9test) Once completed, your configuration will be written to /Users/sammy/d9test/.ddev/config.yaml Created docroot at /Users/sammy/d9test/web You have specified a project type of drupal9 but no project of that type is found in /Users/sammy/d9test/web Ensuring write permissions for d9new No settings.php file exists, creating one Existing settings.php file includes settings.ddev.php Configuration complete. You may now run 'ddev start'.

      Debido a que pasó --project-type=drupal9 a su comando ddev config, DDEV creó varios subdirectorios y archivos que representan la organización predeterminada para un sitio web Drupal. El árbol de directorio de su proyecto ahora tendrá este aspecto:

      A Drupal 9 directory tree

      .
      ├── .ddev
      │   ├── .gitignore
      │   ├── config.yaml
      │   ├── db-build
      │   │   └── Dockerfile.example
      │   └── web-build
      │       └── Dockerfile.example
      └── web
          └── sites
              └── default
                  ├── .gitignore
                  ├── settings.ddev.php
                  └── settings.php
      
      6 directories, 7 files
      

      .ddev/ será la carpeta principal para la configuración ddev. web/ será el docroot para su nuevo proyecto; contendrá varios archivos settings. específicos. Ahora tiene el andamio inicial para su nuevo proyecto Drupal.

      Su siguiente paso es iniciar su plataforma, que creará los contenedores necesarios y las configuraciones de red. DDEV vincula los puertos 80 y 443, de forma que, si está ejecutando un servidor web como Apache en su equipo, o cualquier otra cosa que utilice esos puertos, detenga esos servicios antes de continuar.

      Utilice el comando ddev start para iniciar su plataforma:

      Esto creará todos los contenedores basados en Docker para su proyecto, lo que incluye un contenedor web, un contenedor de base de datos y phpmyadmin. Cuando la inicialización se complete, verá un resultado similar a este (el número de su puerto podría ser diferente):

      Output

      ... Successfully started d9test Project can be reached at http://d9test.ddev.site http://127.0.0.1:32773

      Nota: Recuerde que DDEV está iniciando los contenedores Docker en segundo plano. Si desea ver esos contenedores o verificar que se estén ejecutando, siempre puede usar el comando docker ps:

      Junto con cualquier otro contenedor que esté ejecutando actualmente, encontrará cuatro nuevos contenedores, cada uno con una imagen diferente: php-myadmin, ddev-webserver, ddev-router y ddev-dbserver-mariadb.

      ddev start ha creado correctamente sus contenedores y le ha dado un resultado con dos URL. Aunque este resultado dice que “puede llegar a su proyecto en http://d9test.ddev.site y http://127.0.0.1:32773, visitar estas URL ahora provocará un error. Desde Drupal 8, el núcleo de Drupal y las dependencias similares a función de módulos contrib Por tanto, primero deberá terminar de instalar Drupal usando Composer, el administrador de paquetes para proyectos PHP antes de cargar nada en su navegador web.

      Una de las funciones más útiles y elegantes de DDEV es que puede pasar comandos Composer a través de la CLI de DDEV y en su entorno en contenedores. Esto significa que puede separar la configuración específica de su equipo de su entorno de desarrollo. Ya no tiene que administrar los diversos problemas de ruta de archivo, dependencia y versión que generalmente acompañan al desarrollo PHP local. Además, puede cambiar de contexto rápidamente entre múltiples proyectos usando diferentes marcos y pilas tecnologías con un esfuerzo mínimo.

      Utilice el comando ddev composer para descargar drupal/recommended-project. Esto descargará el núcleo de Drupal, sus bibliotecas y otros recursos relacionados y, luego, creará un proyecto predeterminado:

      • ddev composer create "drupal/recommended-project"

      Ahora descargue un componente final llamado Drush, o Drupal Shell. Este tutorial solo usará un comando drush, y este tutorial proporciona una alternativa, pero drush es una CLI potente para el desarrollo de Drupal que puede mejorar su eficiencia.

      Utilice ddev-composer para instalar drush:

      • ddev composer require "drush/drush"

      Ahora ha creado un proyecto Drupal 9 predeterminado y ha instalado drush. Ahora verá su proyecto en un navegador y configurará los ajustes de su sitio web.

      Paso 3: Configurar su proyecto Drupal 9

      Ahora que instaló Drupal 9 puede visitar su nuevo proyecto en su navegador. Para hacer esto, puede volver a ejecutar ddev start y copiar una de las dos URL que produce, o puede usar el siguiente comando, que abrirá su sitio automáticamente en una nueva ventana del navegador.

      Encontrará el asistente estándar de instalación de Drupal.

      Instalador de Drupal 9 desde navegador

      Aquí tiene dos opciones. Puede usar esta UI y seguir el asistente durante la instalación, o puede volver a su terminal y pasar un comando drush a través de ddev. Esta última opción automatizará el proceso de instalación y establecerá admin como su nombre de usuario y contraseña.

      Opción 1: Usar el asistente

      Vuelva al asistente en su navegador. Bajo Choose language (Seleccionar idioma), seleccione un idioma en el menú desplegable y haga clic en Save and continue (Guardar y continuar). Ahora seleccione un perfil de instalación. Puede elegir entre Standard (Estándar), Minimal (Mínima) y Demo. Seleccione la opción que desee y haga clic en Save and continue (Guardar y continuar). Drupal verificará automáticamente sus requisitos, configurará una base de datos e instalará su sitio. Su último paso es personalizar algunas configuraciones. Añada un nombre de sitio y una dirección de correo electrónico que termine en su dominio. A continuación, elija un nombre de usuario y una contraseña. Elija una contraseña segura y mantenga sus credenciales en algún lugar seguro. Por último, añada una dirección de correo electrónico privada que compruebe regularmente, complete los ajustes regionales y pulse Save and continue (Guardar y continuar).

      Mensaje de bienvenida de Drupal 9 con una advertencia sobre permisos

      Su nuevo sitio se cargará con un mensaje de bienvenida.

      Opción 2: Usar la línea de comandos

      Desde el directorio raíz de su proyecto, ejecute este comando ddev exec para instalar un sitio de Drupal predeterminado usando drush:

      • ddev exec drush site:install --account-name=admin --account-pass=admin

      Esto creará su sitio de la misma manera que el asistente lo hará pero con algunas configuraciones de texto estándar. Su nombre de usuario y contraseña serán admin.

      Ahora abra el sitio para verlo en su navegador:

      Ahora está listo para comenzar a crear su sitio web, pero se considera una buena práctica comprobar que sus permisos son correctos para el directorio /sites/web/default. Aunque está trabajando localmente, esto no es un problema significativo, pero si transfiere estos permisos a un servidor de producción, supondrán un riesgo de seguridad.

      Paso 4: Comprobar sus permisos

      Durante la instalación del asistente, o cuando se cargue por primera vez su página de bienvenida, es posible que vea una advertencia sobre los ajustes de los permisos en su directorio /sites/web/default y un archivo dentro de ese directorio: settings.php.

      Tras ejecutarse la secuencia de comandos de instalación, Drupal intentará configurar los permisos del directorio web/sites/default a read (lectura) y execute (ejecutar) para todos los grupos: este es un ajuste de permisos 555. También intentará configurar permisos para default/settings.php a solo lectura o 444. Si aparece esta advertencia, ejecute estos dos comandos chmod desde el directorio raíz de su proyecto. No hacerlo plantea un riesgo de seguridad:

      • chmod 555 web/sites/default
      • chmod 444 web/sites/default/settings.php

      Para verificar que tiene los permisos correctos, ejecute este comando ls con los conmutadores a, l, h y d:

      • ls -alhd web/sites/default web/sites/default/settings.php

      Compruebe que sus permisos coinciden con el siguiente resultado:

      Output

      dr-xr-xr-x 8 sammy staff 256 Jul 21 12:56 web/sites/default -r--r--r-- 1 sammy staff 249 Jul 21 12:12 web/sites/default/settings.php

      Ahora está listo para desarrollar un sitio web Drupal 9 en su equipo local.

      Paso 5: Crear su primera publicación en Drupal

      Para probar algunas de las funciones de Drupal, creará una publicación usando la IU de la web.

      Desde la página inicial de su sitio, haga clic en el botón Contenido en la parte izquierda del menú superior. Ahora haga clic en el botón azul add content (añadir contenido). Aparecerá una nueva página. Haga clic en Article (Artículo) y aparecerá otra página.

      Instrucción Crear artículo de Drupal 9

      Añada el título y el contenido que desee. Puede añadir una imagen también, como uno de los fondos de pantalla de DigitalOcean. Cuando esté listo, haga clic en el botón save (guardar) azul.

      Su primera publicación aparecerá en su sitio web.

      Drupal 9 creó una publicación

      Ahora está desarrollando un sitio web Drupal 9 en su equipo local sin interactuar con un servidor gracias a Docker y DDEV. En el siguiente paso, administrará el contenedor DDEV para acomodar su flujo de trabajo.

      Paso 6: Administrar el contenedor de DDEV

      Cuando haya terminado de desarrollar su proyecto o cuando desee tomarse un descanso, puede detener su contenedor DDEV sin preocuparse sobre la pérdida de datos. DDEV puede administrar el cambio rápido de contexto entre muchos proyectos, y esta es una de sus funciones más útiles. Su código y datos siempre se conservan en el directorio de su proyecto, incluso tras detener o eliminar el contenedor de DDEV.

      Para liberar recursos, puede detener DDEV en cualquier momento. Desde el directorio raíz de su proyecto, ejecute el siguiente comando:

      DDEV está disponible globalmente, de forma que puede ejecutar comandos ddev desde cualquier lugar, siempre que especifique el proyecto DDEV:

      También puede ver todos sus proyectos a la vez usando ddev list:

      DDEV incluye muchos otros comandos útiles.

      Puede reiniciar DDEV y continuar desarrollando localmente en cualquier momento.

      Conclusión

      En este tutorial, utilizó Docker y el poder de la creación de contenedores para desarrollar un sitio Drupal localmente con la ayuda de DDEV. DDEV también se integra bien con numerosos IDE, y ofrece depuración PHP integrada para Atom, PHPStorm y Visual Studio Code (vscode). Desde aquí, puede aprender más sobre crear entornos de desarrollo para Drupal con DDEV o desarrollar otros marcos PHP como WordPress.



      Source link