EzDevInfo.com

Autoload

A lightweight php namespace aware autoload generator

Is autoload thread-safe in Ruby 1.9?

It seems to me that the Ruby community has been freaking out a little about autoload since this famous thread, discouraging its use for thread safety reasons.

Does anyone know if this is no longer an issue in Ruby 1.9.1 or 1.9.2? I've seen a bit of talk about wrapping requires in mutexes and such, but the 1.9 changelogs (or at least as much as I've been able to find) don't seem to address this particular question. I'd like to know if I can reasonably start autoloading in 1.9-only libraries without any reasonable grief.

Thanks in advance for any insights.


Source: (StackOverflow)

Autoload with namespaces in PHP 5.3?

How do you use _autoload in PHP 5.3 with namespaces? I have a main autoload function in a namespace separate from my script. I'm also calling a class with a different namespace. (It's not surprising, but) It's not finding the autoload function. Do I have to recreate the autoload function for each namespace? That seems suboptimal.

Thanks in advance for any help!


Source: (StackOverflow)

Advertisements

How do I use PHP namespaces with autoload?

I get this error when I try to use autoload and namespaces:

Fatal error: Class 'Class1' not found in /usr/local/www/apache22/data/public/php5.3/test.php on line 10

Can anyone tell me what I am doing wrong?

Here is my code:

Class1.php:

<?php

namespace Person\Barnes\David
{
    class Class1
    {
        public function __construct()
        {
            echo __CLASS__;
        }
    }
}

?>

test.php:

<?php

function __autoload($class)
{
    require $class . '.php';
}

use Person\Barnes\David;

$class = new Class1();

?>

Source: (StackOverflow)

Perl's AUTOLOAD in Python (__getattr__ on a module)

In the past I've used perl's AUTOLOAD facility for implementing lazy loading of symbols into a namespace, and wanted the same functionality in python.

Traditionally the closest you appear to be able to get is to use a class and a __getattr__ class to achieve this sort of thing. However I've also tried rummaging around in sys.modules, and come up with this:

# mymod.py
def greet(greeting="Hello World"):
   print greeting

class AutoLoad(object):
    def __init__(self, mod_name):
        super(autoload, self).__init__()
        self.wrapped_name = mod_name
        self.wrapped = sys.modules[mod_name]
    def __getattr__(self, name):
        try:
            return getattr(self.wrapped, name)
        except AttributeError:
            def f():
                greet(name + " " + self.wrapped_name)
            return f

if __name__ != "__main__":
    import sys
    sys.modules[__name__] = AutoLoad(__name__)

This does work the way I'd like from a user perspective:

~> python
Python 2.5.1 (r251:54863, Jan 10 2008, 18:01:57)
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymod
>>> mymod.hello()
hello mymod
>>> from mymod import Hello_World
>>> Hello_World()
Hello_World mymod

But it strikes me - is there a standard approach that people tend to use for autoloading in python?

Secondly, a question for experienced python developers really is "does this strike you as good or bad practice"? I'm a reasonably experienced python developer, and it strikes me as really useful, but it strikes me as borderline and interested in whether this can be viewed as good practice, bad practice or similar.


Source: (StackOverflow)

from camel case to underscore case conversion with php __autoload() function

PHP manual suggests to autoload classes like

function __autoload($class_name){
 require_once("some_dir/".$class_name.".php");
}

and this appoach works fine to load class FooClass saved in the file my_dir/FooClass.php like

class FooClass{
  //some implementation
}

here is my question: how can I make it possible to use _autoload() function and access FooClass saved in the file my_dir/foo_class.php? thanks for your help.

[Note: 1. the CamelCase and under_score notations on the files 2. the manual link is : http://www.php.net/manual/en/language.oop5.autoload.php ].


Source: (StackOverflow)

php5.4 autoloading traits

Are traits in php5.4 subject to autoloading?

I've not yet got an environment to test in, but I can't see any mention of it on __autoload at php.net or on the traits page, but it seems traits behave like classes in some regards.

Has anyone tried this yet?

UPDATE:

I found a request here: https://bugs.php.net/bug.php?id=61265 (2012-03-03 13:10 UTC)

that seems to suggest it does work, but not explicitly. Can anyone confirm that a straight __autoload() will be called for a missing trait?

UPDATE: Confirmed - it works as expected - __autoload will fetch traits, although getting php5.4 to work first time seems to be bigger challenge.

Thanks, MyStream


Source: (StackOverflow)

autoload and multiple directories

I've just been looking at php's autoload() function. Seems a nice idea, but I'm not sure how it handles multiple directories. My current development basically has a library directory structure grouping classes into subdirectories by operation. I'm wondering I have to declare a include() for each directory ... which I really hope I don't have to do.

Can you advise - thanks


Source: (StackOverflow)

Rails3 not reloading code in lib while in development mode

THE SITUATION:

  1. I have code in lib/foo/bar.rb with a simple method defined as such:

    module Foo
      class Bar
        def test
          "FooBar"
        end
      end
    end
    
  2. In my helper, FooBarHelper, I have:

    require `lib/foo/bar`
    module FooBarHelper
      def test_foo_bar
        fb = Foo::Bar.new
        fb.test
      end
    end
    
  3. In my view, I call this helper method like so:

    <%= test_foo_bar =>
    
  4. In my config/environments/development.rb, I added the directory to my config.autoload_paths:

    config.autoload_paths += ["#{config.root}/lib/foo"]
    

THE PROBLEM:

When I change the return value of Foo::Bar.test to, for example, "MODIFIED FOOBAR", the original return value, "FooBar", is still being displayed on the view and not the new value.

Since I'm in development mode, shouldn't the code reload the code on every request?

Could someone tell me what I'm missing?

Thanks!


Source: (StackOverflow)

Autoload classes from different folders

This is how I autoload all the classes in my controllers folder,

# auto load controller classes
    function __autoload($class_name) 
    {
        $filename = 'class_'.strtolower($class_name).'.php';
        $file = AP_SITE.'controllers/'.$filename;

        if (file_exists($file) == false)
        {
            return false;
        }
        include ($file);
    }

But I have classes in models folder as well and I want to autoload them too - what should I do? Should I duplicate the autoload above and just change the path to models/ (but isn't this repetitive??)?

Thanks.

EDIT:

these are my classes file names in the controller folder:

class_controller_base.php
class_factory.php
etc

these are my classes file names in the model folder:

class_model_page.php
class_model_parent.php
etc

this is how I name my controller classes class usually (I use underscores and lowcaps),

class controller_base 
{
...
}

class controller_factory
{
...
}

this is how I name my model classes class usually (I use underscores and lowcaps),

class model_page 
    {
    ...
    }

    class model_parent
    {
    ...
    }

Source: (StackOverflow)

__autoload not respected when testing with PHPUnit

How can I make PHPUnit respect __autoload functions?

For example, I have these three files:

loader.php

function __autoload($name)
{
    echo "foo\n";
    require_once("$name.php");
}

test.php

require_once("loader.php");

class FooTest extends PHPUnit_Framework_TestCase
{
    function testFoo()
    {
        new Foo();
    }
}

foo.php

require_once("loader.php");
new Foo();

As expected php foo.php errors out, saying that file "Foo.php" doesn't exist. The testFoo() function however errors out by saying that there is no such class as Foo, and never echos the "foo\n" line.


Source: (StackOverflow)

Why use a PSR-0 or PSR-4 autoload in composer if classmap is actually faster?

I understand that you can use either a PSR standard to locate files, or tell composer a directory to scan for classes. The documentation recommends using the PSR-4 standard. There is also an option for composer to create an optimized autoloader, which basically generates a full classmap. So why should one use PSR-4 at all if the best way to load is with a classmap?

It makes sense to me to keep the directory structure, since that is a good way to organize anyway. However, it seems like the logical option would be to use PSR-4 loading on development machines, and then classmap for the production environment. That way, you don't have to rebuild your classmap every time you create a new class, but the production environment creates a complete one as a part of the deployment process without an additional call to

./composer.phar dumpautoloader -o

Source: (StackOverflow)

PHP Autoloading with SplClassLoader?

I'm learning about namespaces in PHP 5.3 and I would like to use Namespaces Autoloading. I found this SplClassLoader class, but I can't figure out how it works.

Let's say I have directory structure like this:

system
  - framework
    - http
      - request.php
      - response.php
index.php
SplClassLoader.php

How do I enable class autoloading? What namespaces should request.php and response.php have?

This is the request.php:

namespace framework\http;

class Request
{
    public function __construct()
    {
        echo __CLASS__ . " constructer!";
    }
} 

And this is the response.php:

namespace framework\http;

class Request
{            
    public function __construct()
    {      
        echo __CLASS__ . " constructed!";                
    }           
}   

And in index.php I have:

require_once("SplClassLoader.php");
$loader = new SplClassLoader('framework\http', 'system/framework');
$loader->register();

$r = new Request();

I get this error message:

Fatal error: Class 'Request' not found in C:\wamp\apache\htdocs\php_autoloading\index.php on line 8

Why is this not working? How can I use SplClassLoader in my projects so it loads/requires my classes, and how should I setup and name folders and namespaces?


Source: (StackOverflow)

Using PHP namespaces in a Zend Framework (v1) application

Is it possible in the current stable version of the Zend Framework (1.11), to work with application classes using PHP namespaces?

Application\Form\Abc instead of Application_Form_Abc
Application\Model\Xyz instead of Application_Model_Xyz
etc.

Starting from v1.10, ZF supports autoloading namespaces, and it's working fine when including namespaced libraries, but I was unsuccessful when trying to do the same job with application classes.


Source: (StackOverflow)

Adding a Custom Form Element to an Adminhtml Form

Is there a way to add a custom form element to a Magento Adminhtml form without placing the custom element in the lib/Varian folder?

I've tracked down the code that's essentially a Varian_Data_Form_Element_ factory

public function addField($elementId, $type, $config, $after=false)
{
    if (isset($this->_types[$type])) {
        $className = $this->_types[$type];
    }
    else {
        $className = 'Varien_Data_Form_Element_'.ucfirst(strtolower($type));
    }
    $element = new $className($config);
    $element->setId($elementId);
    if ($element->getRequired()) {
        $element->addClass('required-entry');
    }
    $this->addElement($element, $after);
    return $element;
}

So, if I'm reading this correctly, I ensure that an EAV attribute's frontend returns a specific fieldType, (such as supertextfield) and the system will instantiate/render a Varien_Data_Form_Element_Supertextfield when displaying this attribute's editing form.

This is well and good, but it means I need to include my custom form element in the lib/Varian folder hierarchy. Given how module oriented Magento is, it seems like this is doing it wrong.

I realize I could jank around with a custo autoloader or symlinks in the lib, but I'm primarily interested in learning if there's

  1. A canonical way to add custom form elements for attributes

  2. A canonical way to customize the Magento autoloader.


Source: (StackOverflow)