Zend Framework 2 provides console abstraction layer, which works around various bugs and limitations in operating systems. It handles displaying of colored text, retrieving console window size, charset and provides basic line drawing capabilities.
See also
Console Adapters can be used for a low-level access to the console. If you plan on building functional console applications you do not normally need to use adapters. Make sure to read about console MVC integration first, because it provides a convenient way for running modular console applications without directly writing to or reading from console window.
If you are using MVC controllers you can obtain Console adapter instance using Service Manager.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | namespace Application;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Console\Adapter\AdapterInterface as Console;
use Zend\Console\Exception\RuntimeException;
class ConsoleController extends AbstractActionController
{
public function testAction()
{
$console = $this->getServiceLocator()->get('console');
if (!$console instanceof Console) {
throw new RuntimeException('Cannot obtain console adapter. Are we running in a console?');
}
}
}
|
If you are using Zend\Console without MVC, we can get adapter using the following code:
1 2 3 4 5 6 7 8 | use Zend\Console\Console;
use Zend\Console\Exception\RuntimeException as ConsoleException;
try {
$console = Console::getInstance();
} catch (ConsoleException $e) {
// Could not get console adapter - most likely we are not running inside a console window.
}
|
Note
For practical and security reasons, Console::getInstance() will always throw an exception if you attempt to get console instance in a non-console environment (i.e. when running on a HTTP server). You can override this behavior by manually instantiating one of Zend\Console\Adapter\* classes.
Note
For UTF-8 enabled consoles (terminals) dimensions represent the number of multibyte characters (real characters).
Note
On consoles with virtual buffers (i.e. MS Windows Command Prompt) width and height represent visible (real) size, without scrolling the window. For example - if the window scrolling width is 120 chars, but it’s real, visible width is 80 chars, getWidth() will return 80.
The source code of this file is hosted on GitHub. Everyone can update and fix errors in this document with few clicks - no downloads needed.