Funciones simples.php o dividido en muchos archivos pequeños?

13

Estoy creando un marco simple con opciones de tema. He dividido trozos de código dentro de functions.php y lo he colocado dentro de una estructura de carpetas específica.

Ahora en mi archivo principal functions.php , solo tengo require_once llamadas a estos archivos.

Pero por el bien de la discusión, digamos que terminaré con 20 archivos para incluir.

PREGUNTAS:

  1. ¿Esto tiene efecto en el rendimiento de WP de una manera visible?
  2. ¿Es mejor mantenerlo todo dentro de 1 archivo (functions.php)
  3. ¿Cuál es la mejor manera de hacer esto?

Gracias.

    
pregunta MegaMan 28.08.2013 - 15:03

2 respuestas

11
  

1. ¿Esto tiene un efecto en el rendimiento de WP de manera visible?

IF tendría un efecto real en algunos archivos pequeños, entonces tendría un efecto que tiene un impacto menor que WP: PHP y el rendimiento del servidor. ¿Realmente tiene un efecto? Realmente no. Pero todavía puedes simplemente comenzar a hacer pruebas de rendimiento.

  

2. ¿Es mejor mantenerlo todo dentro de 1 archivo (functions.php)

Ahora la pregunta es "¿Qué es mejor"? ¿Del tiempo total de carga de los archivos? ¿Desde el punto de vista de la organización de archivos? De todos modos, no hace ninguna diferencia. Hágalo de una manera que no pierda la visión general y pueda mantener el resultado de una manera que sea agradable para usted.

  

3. ¿cuál es la mejor manera de hacerlo?

Lo que normalmente hago es simplemente enlazar en algún lugar de ( plugins_loaded , after_setup_theme , etc. - depende de lo que necesites) y luego solo requiere que todos:

foreach ( glob( plugin_dir_path( __FILE__ ) ) as $file )
    require_once $file;

De todos modos, también puedes hacerlo un poco más complicado y flexible. Eche un vistazo a ese ejemplo:

<?php

namespace WCM;

defined( 'ABSPATH' ) OR exit;

class FilesLoader implements \IteratorAggregate
{
    private $path = '';

    private $files = array();

    public function __construct( $path )
    {
        $this->setPath( $path );
        $this->setFiles();
    }

    public function setPath( $path )
    {
        if ( empty( $this->path ) )
            $this->path = \plugin_dir_path( __FILE__ ).$path;
    }

    public function setFiles()
    {
        return $this->files = glob( "{$this->getPath()}/*.php" );
    }

    public function getPath()
    {
        return $this->path;
    }

    public function getFiles()
    {
        return $this->files;
    }

    public function getIterator()
    {
        $iterator = new \ArrayIterator( $this->getFiles() );
        return $iterator;
    }

    public function loadFile( $file )
    {
        include_once $file;
    }
}

Es una clase que básicamente hace lo mismo (necesita PHP 5.3+). El beneficio es que es un poco más detallado, por lo que puede cargar archivos de carpetas que necesita para realizar una tarea específica:

$fileLoader = new WCM\FilesLoader( 'assets/php' );

foreach ( $fileLoader as $file )
    $fileLoader->loadFile( $file );

Actualizar

Como vivimos en un nuevo mundo de PHP v5.2, podemos hacer uso de \FilterIterator . Ejemplo de la variante más corta:

$files = new \FilesystemIterator( __DIR__.'/src', \FilesystemIterator::SKIP_DOTS );
foreach ( $files as $file )
{
    /** @noinspection PhpIncludeInspection */
    ! $files->isDir() and include $files->getRealPath();
}

Si tienes que mantenerte con PHP v5.2, entonces puedes seguir con \DirectoryIterator y prácticamente el mismo código.

    
respondido por el kaiser 28.08.2013 - 16:47
1

He reelaborado @kaiser para responder un poco a mis necesidades: pensé que lo compartía. Quería más opciones, esas se explican dentro del código y en el ejemplo de uso a continuación.

Código:

<?php

defined( 'ABSPATH' ) OR exit;

/**
 * Functions_File_Loader
 * 
 * Makes it possible to clutter the functions.php into single files.
 * 
 * @author kaiser
 * @author ialocin
 * @link http://wordpress.stackexchange.com/q/111970/22534
 *
 */

class Functions_File_Loader implements IteratorAggregate {

    /**
     * @var array
     */
    private $parameter = array();

    /**
     * @var string
     */
    private $path;

    /**
     * @var string
     */
    private $pattern;

    /**
     * @var integer
     */
    private $flags;

    /**
     * @var array
     */
    private $files = array();

    /**
     * __construct
     *
     * @access public 
     * @param array $parameter
     */
    public function __construct( $parameter ) {
        $this->set_parameter( $parameter );
        $this->set_path( $this->parameter[ 'path' ] );
        $this->set_pattern( $this->parameter[ 'pattern' ] );
        $this->set_flags( $this->parameter[ 'flags' ] );
        $this->set_files();
    }

    /**
     * set_parameter
     *
     * @access public 
     * @param array $parameter
     */
    public function set_parameter( $parameter ) {
        if ( empty( $parameter ) )
            $this->parameter = array('','','');
        else
            $this->parameter = $parameter;
    }

    /**
     * get_parameter
     *
     * @access public 
     * @return array
     */
    public function get_parameter() {
        return $this->parameter;
    }

    /**
     * set_path
     *
     * defaults to get_stylesheet_directory()
     * 
     * @access public 
     * @param string $path
     */
    public function set_path( $path ) {
        if ( empty( $path ) )
            $this->path = get_stylesheet_directory().'/';
        else
            $this->path = get_stylesheet_directory().'/'.$path.'/';
    }

    /**
     * get_path
     *
     * @access public 
     * @return string
     */
    public function get_path() {
        return $this->path;
    }

    /**
     * set_pattern
     *
     * defaults to path plus asterisk »*«
     * 
     * @access public 
     * @param string $pattern
     */
    public function set_pattern( $pattern ) {
        if ( empty( $pattern ) )
            $this->pattern = $this->get_path() . '*';
        else
            $this->pattern = $this->get_path() . $pattern;
    }

    /**
     * get_pattern
     *
     * @access public 
     * @return string
     */
    public function get_pattern() {
        return $this->pattern;
    }

    /**
     * set_flags
     *
     * @access public 
     * @param integer $flags
     */
    public function set_flags( $flags ) {
        if ( empty( $flags ) )
            $this->flags = '0';
        else
            $this->flags = $flags;
    }

    /**
     * get_flags
     *
     * @access public 
     * @return integer
     */
    public function get_flags() {
        return $this->flags;
    }


    /**
     * set_files
     *
     * @access public 
     */
    public function set_files() {
        $pattern = $this->get_pattern();
        $flags = $this->get_flags();
        $files = glob( $pattern, $flags );
        $this->files = $files;
    }


    /**
     * get_files
     *
     * @access public 
     * @return array
     */
    public function get_files() {
        return $this->files;
    }

    /**
     * getIterator
     * 
     * This function name has to be kept
     * 
     * @access public 
     * @return void
     */
    public function getIterator() {
        $iterator = new ArrayIterator( $this->get_files() );
        return $iterator;
    }

    /**
     * load_file
     *
     * @access public 
     * @param string $file
     */
    public function load_file( $file ) {
        include_once $file;
    }
}


Ejemplo de uso:

$parameter = array(
        // define path relative to get_stylesheet_directory()
        // optional, defaults to get_stylesheet_directory()
        'path' => 'includes/plugins',
        // optional, defaults to asterisk »*«
        // matches all files ending with ».php« 
        // and not beginning with »_«, good for quickly deactivating 
        // directories searched are »path« and »subfolders«
        // Additional examples:
        // '{*/,}{[!_],}func-*.php' same as above but for files with a prefix
        // '[!_]*.php' php files in defined »path«, not beginning with »_« 
        'pattern' => '{*/,}[!_]*.php',
        // optional, defaults to 0
        // needed if for example brackets are used
        // more information: http://www.php.net/manual/en/function.glob.php
        'flags' => GLOB_BRACE
    );
// create object
$functionsfileloader = new Functions_File_Loader( $parameter );
// load the files
foreach ( $functionsfileloader as $file ) {
    $functionsfileloader->load_file( $file );
}
    
respondido por el Nicolai 20.04.2014 - 23:35

Lea otras preguntas en las etiquetas