VIII. Funciones COM y .Net (Windows)

Introducción

COM es un acrónimo para Component Object Model (Modelo de Objetos por Componentes); es una capa orientada a objetos (asi como servicios asociados) que cubre la especificación DCE RPC (un estándar abierto) y define una convención común de llamado que permite que código escrito en cualquier lenguaje pueda llamar e inter-operar con código escrito en cualquier otro lenguaje (provisto que ambos lenguajes hagan uso de COM). No solo es posible escribir el código en cualquier lenguaje, también es cierto que no necesita ser parte del mismo ejecutable; el código puede ser cargado desde un recurso DLL, encontrarse en otro proceso corriendo en la misma máquina, o, mediante DCOM (COM Distribuido), encontrarse en otro proceso en una máquina remota, todo esto sin requerir que su código sepa siquiera en dónde reside el componente.

Existe un sub-conjunto de COM conocido como Automatización OLE que se compone de un grupo de interfaces OLE que permiten los enlaces flexibles con objetos COM, de modo que puedan ser susceptibles a introspección y llamados en tiempo de ejecución sin conocimientos en tiempo de compilación sobre el modo de operación del objeto. La extensión COM de PHP utiliza las interfaces de Automatización OLE para permitirle crear y llamar objetos compatibles desde sus scripts. Técnicamente hablando, ésta debería ser llamada la "Extensión de Automatización OLE para PHP", ya que no todos los objetos COM son compatibles con OLE.

Ahora bien, ¿porqué querría o debería usar COM? COM es una de las formas principales de unir aplicaciones y componentes en la plataforma Windows; mediante el usa de COM usted puede iniciar Microsoft Word, llenar una plantilla de documento y guardar el resultado como un documento Word y enviarlo a un visitante de su sitio web. También puede usar COM para realizar tareas administrativas para su red y para configurar su servidor web (IIS); tales son apenas los usos más comunes; usted puede hacer mucho más con COM.

A partir de PHP 5, esta extensión (y su documentación) fue re-escrita por completo y se ha eliminado gran parte del material confuso e inútil. Adicionalmente, se ofrece soporte para la creación de instancias y ensambles .Net usando la capa de interoperabilidad COM ofrecida por Microsoft.

Por favor lea este artículo para una vista general de los cambios en ésta extensión en PHP 5.

Requerimientos

Las funciones COM se encuentran disponibles únicamente para la versión Windows de PHP.

El soporte para .Net requiere PHP 5 y el entorno de desarrollo .Net.

Instalación

No se necesita ninguna instalación para usar estas funciones, son parte del núcleo de PHP.

La versión para Windows de PHP tiene soporte nativo para esta extensión. No se necesita cargar ninguna extensión adicional para usar estas funciones.

Usted es responsable de la instalación del soporte para los varios objetos COM que piensa usar (tales como MS Word); nosotros no incluimos todos éstos con PHP, ni podemos hacerlo.

For Each

A partir de PHP 5, usted puede usar la sentencia la sección de nombre foreach en Capítulo 11 de PHP para iterar sobre los contenidos de un IEnumVariant COM/OLE estándar. En términos más simples, esto quiere decir que puede usar foreach en aquellas situaciones en donde podría haber usado For Each en código VB/ASP.

Ejemplo 1. For Each en ASP

<%
Set objetoDominio = GetObject("WinNT://Domain")
For Each obj in objetoDominio
  Response.Write obj.Name & "<br />"
Next
%>

Ejemplo 2. while() ... Next() en PHP 4

<?php
$objetoDominio
= new COM("WinNT://Domain");
while (
$obj = $objetoDominio->Next()) {
   echo
$obj->Name . "<br />";
}
?>

Ejemplo 3. foreach en PHP 5

<?php
$objetoDominio
= new COM("WinNT://Domain");
foreach (
$objetoDominio as $obj) {
   echo
$obj->Name . "<br />";
}
?>

Matrices y propiedades COM tipo-matriz

Muchos objetos COM exponen sus propiedades como matrices, o usando un acceso estilo-matriz. En PHP 4, es posible usar la sintaxis de matrices de PHP para leer/escribir tales propiedades, pero sólo es posible manipular una dimensión. Si desea leer una propiedad multi-dimensional, puede crear el acceso en forma de un llamado de función, en donde cada parámetro representa cada parámetro del acceso a la matriz, aunque no hay forma de escribir tal tipo de propiedad.

PHP 5 introduce las siguientes características nuevas para facilitar su vida:

  • Acceso a matrices multi-dimensionales, o propiedades COM que requieren múltiples parámetros usando la sintaxis de matrices de PHP. También puede escribir o definir propiedades usando ésta técnica.

  • Iterar a través de SafeArrays ("verdaderas" matrices) usando la estructura de control la sección de nombre foreach en Capítulo 11. Esto funciona ya que los SafeArrays incluyen información sobre su tamaño. Si una propiedad estilo-matriz implementa IEnumVariant, entonces también puede usar foreach para tales propiedades; eche un vistazo a la sección de nombre For Each para más información sobre este tema.

Excepciones (PHP 5)

Esta extensión arroja instancias de la clase com_exception siempre que se presente un error potencialmente fatal reportado por COM. Todas las excepciones COM tienen una propiedad code bien definida que corresponde con el valor de retorno HRESULT proveniente de las varias operaciones COM. Es posible usar éste código para tomar decisiones programáticas sobre cómo manejar la excepción.

Configuración en tiempo de ejecución

El comportamiento de estas funciones está afectado por los valores definidos en php.ini.

Tabla 1. Com configuration options

NameDefaultChangeable
com.allow_dcom"0"PHP_INI_SYSTEM
com.autoregister_typelib"0"PHP_INI_ALL
com.autoregister_verbose"0"PHP_INI_ALL
com.autoregister_casesensitive"1"PHP_INI_ALL
com.code_page""PHP_INI_ALL
com.typelib_file""PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

A continuación se presenta una corta explicación de las directivas de configuración.

com.allow_dcom

When this is turned on, PHP will be allowed to operate as a D-COM (Distributed COM) client and will allow the PHP script to instantiate COM objects on a remote server.

com.autoregister_typelib

When this is turned on, PHP will attempt to register constants from the typelibrary of objects that it instantiates, if those objects implement the interfaces required to obtain that information. The case sensitivity of the constants it registers is controlled by the com.autoregister_casesensitive configuration directive.

com.autoregister_verbose

When this is turned on, any problems with loading a typelibrary during object instantiation will be reported using the PHP error mechanism. The default is off, which does not emit any indication if there was an error finding or loading the type library.

com.autoregister_casesensitive

When this is turned on (the default), constants found in auto-loaded type libraries will be registered case sensitively. See com_load_typelib() for more details.

com.code_page

It controls the default character set code-page to use when passing strings to and from COM objects. If set to an empty string, PHP will assume that you want CP_ACP, which is the default system ANSI code page.

If the text in your scripts is encoded using a different encoding/character set by default, setting this directive will save you from having to pass the code page as a parameter to the COM class constructor. Please note that by using this directive (as with any PHP configuration directive), your PHP script becomes less portable; you should use the COM constructor parameter whenever possible.

Nota: This configuration directive was introduced with PHP 5.

com.typelib_file

When set, this should hold the path to a file that contains a list of typelibraries that should be loaded on startup. Each line of the file will be treated as the type library name and loaded as though you had called com_load_typelib(). The constants will be registered persistently, so that the library only needs to be loaded once. If a type library name ends with the string #cis or #case_insensitive, then the constants from that library will be registered case insensitively.

Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles solamente cuando la extensión ha sido o bien compilada dentro de PHP o grabada dinámicamente en tiempo de ejecución.

CLSCTX_INPROC_SERVER (integer)

CLSCTX_INPROC_HANDLER (integer)

CLSCTX_LOCAL_SERVER (integer)

CLSCTX_REMOTE_SERVER (integer)

CLSCTX_SERVER (integer)

CLSCTX_ALL (integer)

VT_NULL (integer)

VT_EMPTY (integer)

VT_UI1 (integer)

VT_I2 (integer)

VT_I4 (integer)

VT_R4 (integer)

VT_R8 (integer)

VT_BOOL (integer)

VT_ERROR (integer)

VT_CY (integer)

VT_DATE (integer)

VT_BSTR (integer)

VT_DECIMAL (integer)

VT_UNKNOWN (integer)

VT_DISPATCH (integer)

VT_VARIANT (integer)

VT_I1 (integer)

VT_UI2 (integer)

VT_UI4 (integer)

VT_INT (integer)

VT_UINT (integer)

VT_ARRAY (integer)

VT_BYREF (integer)

CP_ACP (integer)

CP_MACCP (integer)

CP_OEMCP (integer)

CP_UTF7 (integer)

CP_UTF8 (integer)

CP_SYMBOL (integer)

CP_THREAD_ACP (integer)

VARCMP_LT (integer)

VARCMP_EQ (integer)

VARCMP_GT (integer)

VARCMP_NULL (integer)

NORM_IGNORECASE (integer)

NORM_IGNORENONSPACE (integer)

NORM_IGNORESYMBOLS (integer)

NORM_IGNOREWIDTH (integer)

NORM_IGNOREKANATYPE (integer)

NORM_IGNOREKASHIDA (integer)

DISP_E_DIVBYZERO (integer)

DISP_E_OVERFLOW (integer)

MK_E_UNAVAILABLE (integer)

Ver también

Para más información sobre COM, lea la especificación COM o quizás eche un vistazo a la Otra Biblioteca COM Más (YACL por sus siglas en Inglés) de Don Box. Puede encontrar información adicional en nuestro FAQ sobre Capítulo 53. Si está pensando en usar aplicaciones MS Office en el lado del servidor, es buena idea que lea la información encontrada aquí: Consideraciones para la Automatización de Office en el Lado del Servidor.

Tabla de contenidos
COM -- COM class
DOTNET -- DOTNET class
VARIANT -- VARIANT class
com_addref --  Increases the components reference counter [deprecated]
com_create_guid --  Generate a globally unique identifier (GUID)
com_event_sink --  Connect events from a COM object to a PHP object
com_get_active_object --  Returns a handle to an already running instance of a COM object
com_get -- ???
com_invoke -- ???
com_isenum -- Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]
com_load_typelib -- Loads a Typelib
com_load -- ???
com_message_pump --  Process COM messages, sleeping for up to timeoutms milliseconds
com_print_typeinfo --  Print out a PHP class definition for a dispatchable interface
com_propget -- ???
com_propput -- ???
com_propset -- ???
com_release --  Decreases the components reference counter [deprecated]
com_set -- ???
variant_abs --  Returns the absolute value of a variant
variant_add --  "Adds" two variant values together and returns the result
variant_and --  performs a bitwise AND operation between two variants and returns the result
variant_cast --  Convert a variant into a new variant object of another type
variant_cat --  concatenates two variant values together and returns the result
variant_cmp --  Compares two variants
variant_date_from_timestamp --  Returns a variant date representation of a unix timestamp
variant_date_to_timestamp --  Converts a variant date/time value to unix timestamp
variant_div --  Returns the result from dividing two variants
variant_eqv --  Performs a bitwise equivalence on two variants
variant_fix --  Returns the integer portion ? of a variant
variant_get_type -- Returns the type of a variant object
variant_idiv --  Converts variants to integers and then returns the result from dividing them
variant_imp --  Performs a bitwise implication on two variants
variant_int --  Returns the integer portion of a variant
variant_mod --  Divides two variants and returns only the remainder
variant_mul --  multiplies the values of the two variants and returns the result
variant_neg --  Performs logical negation on a variant
variant_not --  Performs bitwise not negation on a variant
variant_or --  Performs a logical disjunction on two variants
variant_pow --  Returns the result of performing the power function with two variants
variant_round --  Rounds a variant to the specified number of decimal places
variant_set_type --  Convert a variant into another type. Variant is modified "in-place"
variant_set --  Assigns a new value for a variant object
variant_sub --  subtracts the value of the right variant from the left variant value and returns the result
variant_xor --  Performs a logical exclusion on two variants