Unique wordpress plugin class, function name [duplicate] - wordpress

What are PHP Namespaces?
What are Namespaces in general?
A Layman answer with an example would be great.

Namespacing does for functions and classes what scope does for variables. It allows you to use the same function or class name in different parts of the same program without causing a name collision.
In simple terms, think of a namespace as a person's surname. If there are two people named "John" you can use their surnames to tell them apart.
The Scenario
Suppose you write an application that uses a function named output(). Your output() function takes all of the HTML code on your page and sends it to the user.
Later on your application gets bigger and you want to add new features. You add a library that allows you to generate RSS feeds. This library also uses a function named output() to output the final feed.
When you call output(), how does PHP know whether to use your output() function or the RSS library's output() function? It doesn't. Unless you're using namespaces.
Example
How do we solve having two output() functions? Simple. We stick each output() function in its own namespace.
That would look something like this:
namespace MyProject;
function output() {
# Output HTML page
echo 'HTML!';
}
namespace RSSLibrary;
function output(){
# Output RSS feed
echo 'RSS!';
}
Later when we want to use the different functions, we'd use:
\MyProject\output();
\RSSLibrary\output();
Or we can declare that we're in one of the namespaces and then we can just call that namespace's output():
namespace MyProject;
output(); # Output HTML page
\RSSLibrary\output();
No Namespaces?
If we didn't have namespaces we'd have to (potentially) change a lot of code any time we added a library, or come up with tedious prefixes to make our function names unique. With namespaces, we can avoid the headache of naming collisions when mixing third-party code with our own projects.

A namespace allows you to place a bunch of code under a name and not have any naming conflicts with classes, functions and constants.
It allows your code to live in that namespace.
PHP uses the somewhat controversial character \ to show namespace levels. People got up in arms because it is also used as an escape character.
To use the namespace in PHP, use something like this at the top of your file.
namespace my\namespace;
You can find a lot more information on the official PHP documentation for namespaces.

Since it’s easier to learn about the keyword “use” by knowing about “namespace”, let me explain namespace first by looking at a basic Laravel project.
There is a controller class with the name: Controller.php which is in the path:
app/Http/Controllers from the project’s root directory
There is also another controller class named: Controller.php, but this one is in the path:
vendor/laravel/framework/src/Illuminate/Routing from the project’s root directory
You don’t need to look at the source code yet if you’re new to php because it can confuse you, instead let me explain to you the part of
it that we care about and will help us understand “namespace” and “use”.
So as a matter of fact, our first controller class:
app/Http/Controllers/Controller.php needs to use the
Second controller class vendor/laravel/framework/src/Illuminate/Routing/Controller.php.
it actually needs to extend this Class in order to have access to its content for handling some crucial routing functionalities.
So how can a class extend another class that has the same name?
class Controller extends Controller? this will NOT work,
unless there is a way to distinguish these two classes and that’s where namespace comes handy and the use keyword
helps to complete the mission of, allowing the usage of; (classes; methods; interfaces and constants), with the same name, in the same scope.
now how is it done in the code? very simple! if we look at app/Http/Controllers/Controller.php source code, we can see at the top of the class
namespace is declared as: namespace App\Http\Controllers, so this is how you give your class a namespace so it can be referenced by other classes
now this looks the same as the path to this class from the project’s root directory, with little difference and that’s the usage of “\” instead of “/“
(same as command prompt in windows),
but there is another difference and that’s the App with capital ‘A’ in the namespace versus ‘app’ with
Lowercase ‘a’ in the path. Also note that namespace is case-sensitive.
So namespace is a separate concept than the path, it can follow the path structure if it helps but it doesn’t have to be exact path to the
class, method, interfaces or constants for example take a look at:
vendor/laravel/framework/src/Illuminate/Routing/Controller.php source code,
we see at the top of the class the namespace is declared as: Illuminate\Routing
now let’s take look at the “use” keyword,
we use, the “use” keyword to make our class aware of a specific class or function that we want to use in our class
so we are not importing or including anything we’re just letting our class know that we will be using a specific class or
method by referencing them by their namespace
let’s take a look at app/Http/Controllers/Controller.php source code,
as you can see from the line: “use Illuminate\Routing\Controller as BaseController”, the “use” keyword followed by namespace
for the target class
(note that Illuminate\Routing\Controller.php and Illuminate\Routing\Controller ‘without .php extension’ are interchangeable)
we can use the “as” keyword along with the “use” keyword to give a specific class, method, interfaces or constants an alias which allows
app/Http/Controllers/Controller.php to extend Illuminate\Routing\Controller.php as BaseController in the line:
“class Controller extends BaseController”.

There are techniques like namespaces in other programming languages (like packages in Java). They are used to be able to have mutliple classes with the same name wihtin a project.
From the php documentation (http://www.php.net/manual/en/language.namespaces.rationale.php):
What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file foo.txt can exist in both directory /home/greg and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/greg directory, we must prepend the directory name to the file name using the directory separator to get /home/greg/foo.txt. This same principle extends to namespaces in the programming world.

A Namespace works like a directory. You know how you can put files in a directory with the same names as files in the parent (or any other) directory? Well, a namespace lets you do that within an application for variables, functions and classes.
There was a bit of a trend in PHP a little while ago for huge classes of static functions. The only way to call any of those functions was by prefixing a call with the class name. This was a primitive attempt at namespaces, but with not very much of the benefits.

Much like directories and files, namespace in PHP serves to group classes, functions, interfaces and constants.
Example:
Filesystem | PHP Namespace
----------------|------------------
/Dir/File.txt | \Namespace\Class
It provides a way of wrapping items from the global space and allows use of plain item name without causing name collision in a program.
It's supported in PHP 5.3.0, PHP 7.
But there are some limits in analogy between PHP namespace and Unix based filesystem:
| Filesystem | PHP Namespace
--------------------------|-----------------------|-------------------------
Cas sensitive | No | Yes
--------------------------|-----------------------|-------------------------
Name with plain number | Yes | No
--------------------------|-----------------------|-------------------------
Path level | Yes | Yes
--------------------------|-----------------------|-------------------------
Plain metacharacters name | Yes | No
The principle extends to namespace in programming word.

Namespace is like packaging many things into a single pack. Imagine a namespace as a drawer in which you can put all kinds of things: a pencil, a ruler, a piece of paper and so forth. To avoid using each other's items, you decide to label the drawers so it's clear what belongs to whom.

A namespace basically lets you put code into a container. This will prevent problems with two functions (as well as classes and variables) that share the same name.
These are useful when working when larger applications to prevent issues with pieces of code sharing the same name.
For example, lets say we wanted two functions called "TheMessage" . These both would print (echo) different messages each.
Normally, this would cause a syntax error, as you cannot have two functions that share the same name.
To fix this, you could put these functions into separate namespaces. This would allow you to use both functions without any errors.

Namespace is used to enclosed group of codes so that they can be used in different places without name conflicts.
Think about this as jQuery no conflict method and you will understand it better.

A namespace is a simple system to control the names in a program.
It ensures that names are unique and won’t lead to any conflict.

You can use namespace to avoid name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
Namespaces also have the ability to alias (or shorten) Extra_Long_Names designed to reduce the first problem, improving readability of source code.
As we all know, namespaces and traits are not new in PHP, but still many php developers don’t use these Great concepts because of their complexity.
So, in this post. I’ll try to clear them with examples.
What are namespace and traits?
How you can implement them in your code to make your code reusable and extensible?
Benefits of namespaces
You can use namespace to avoid name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
Namespaces also have the ability to alias (or shorten) Extra_Long_Names designed to reduce the first problem, improving readability of source code.
Let’s understand namespaces with an example.
create a folder name “php_oops” in htdocs(xampp) or www (xwamp)
create a new folder under root directory named “namespaces”, & then create a file index.php under namespaces folder.
<?php
// FilePath:- namespaces/index.php
// let's say, we have two classes in index,
// here, these two classes have global space
class A
{
function __construct()
{
echo "I am at Global space, Class A";
}
}
class B
{
function __construct()
{
echo "I am at Global space, Class B";
}
}
// now create an object of class and
$object = new A; // unqualified class name
echo "<br/>";
$object = new \B; // fully qualified class name
// output:
I am at Global space, Class A
I am at Global space, Class B
Reference-
https://medium.com/#akgarg007/php-laravel-namespaces-and-traits-01-9540fe2969cb

We often need to give resource a name, a label that will help us understand and talk about what it is. But naming is not just the simple task of assigning a sequence of char­acters. Names serve to distinguish one thing from another.
Even though an identifier refers to a single resource, this does not mean that no two identifiers are identical.
We can prevent or reduce identifier collisions by GUID or adding information about the namespace. namespace is the the domain from which the names or identifiers are selected. When we add namespace to an identifier, we create a qualified names.
Example Time!
suppose there is only one JOHN_SMITH in zip code 99501. There is also only one JOHN_SMITH in zip code 86302. So, when we mention JOHN_SMITH, how do we know which JOHN_SMITH we are talking about?
When we are talking in the context of zip code 99501, and mention JOHN_SMITH, we are talking about the JOHN_SMITH who leaves in zip code 99501.
<?php
namespace zc99501;
const JOHN_SMITH = "John Smith from 99501";
?>
When we are talking in the context of zip code 86302, and mention JOHN_SMITH, we are talking about the JOHN_SMITH who leaves in zip code 86302.
<?php
namespace zc86302;
const JOHN_SMITH = "John Smith from 86302";
?>
Now what happens if one person from zip code 99501 and another person from zip code 86302 want to talk about JOHN_SMITH They have to say JOHN_SMITH from 99501 did this and JOHN_SMITH from 86302 did that.
<?php
namespace zc99501;
const JOHN_SMITH = "John Smith from 99501";
namespace zc86302;
const JOHN_SMITH = "John Smith from 86302";
namespace Test;
echo \zc99501\JOHN_SMITH . PHP_EOL;
echo \zc86302\JOHN_SMITH . PHP_EOL;
?>
Here, \zc99501\JOHN_SMITH and \zc86302\JOHN_SMITH are qualified names.
Another Example.
Suppose in one context we mean Book Title when we use the constant title. And Author Name By name.
<?php
namespace Book;
const title = "Don Quixote";
const name = "Miguel de Cervantes Saavedra";
?>
in another context we mean Title of a Character by title. And the Character's Name By name.
<?php
namespace Character;
const title = "Sir";
const name = "Sancho Panza";
?>
When we want title and name in both context, We have to specifically distinguish between Book Title and Title of a Character. We also have to specifically distinguish between Author Name and Character's Name.
<?php
namespace Book;
const title = "Don Quixote";
const name = "Miguel de Cervantes Saavedra";
namespace Character;
const title = "Sir";
const name = "Sancho Panza";
namespace Test;
echo \Book\title . PHP_EOL;
echo \Book\name . PHP_EOL;
echo \Character\title . PHP_EOL;
echo \Character\name . PHP_EOL;
?>
Here, \Book\title, \Book\name, \Character\title and \Character\name are qualified names.
NOTE: In PHP only four types of code are affected by namespaces: classes, interfaces, functions and constants.
That's that.

Related

Defining Symfony Services to maximize maintainability

I'm working on a big domain, for which maintainability is very important.
There are these general workers called ExcelHandlers that implement ExcelHandlerInterface (more on the interface in the ideas section) and basically get an UploadedFile as their input, upload them wherever they want and return the read data as an associative array. Now I have created this base class ExcelFileHandler which does all of these tasks for all excel files given two arguments:
1. The Directory to upload the file
2. the mapping of the excel columns to the indexes of the associative array.
Some ExcelHandlers might have to extend the ExcelFileHandler and do some more processing, in order to get the associative array of data.
The UploadedFile is always passed to the ExcelHandler from the controller.
Now here is the question. Given the generic structure of the ExcelFileHandler how should I define services for specific ExcelHandlers given that some only differ with the original one in the directory to upload the file and the mapping array.
My Ideas:
1. The first approach involves giving the directory and the mapping as the function arguments to ExcelHandleInterface::handle this will make the prototype something like handle(UploadedFile $file, array $mapping, $dir), $mapping and $dir are given to the function as arguments and passed to the handler by the controllers which has the parameters as constructor injections.
2.1 Defining the prototype of handle to be handle(UploadedFile $file), this would require the ExcelHandlers to have knowledge of $dir and $mapping. $dir will always be injected from the constructor.
2.1.1 Foreach individual ExcelHandler in the application, define a separate class e.g: UserExcelHandler, ProductExcelHandler, .... Which extend the ExcelFileHandler and leaves us again with two choices.
2.1.1.1 inject $mapping from outside. e.g:
// in the child class
public function __construct($dir, $mapping){
parent::__construct($dir, $mapping);
}
2.1.1.2 define $mapping in the constructor of the child class. e.g:
// in the child class
public function __construct($dir){
$mapping = array(0 => 'name', 1 => 'gender');
parent::__construct($dir, $mapping);
}
2.1.2 Not to create a class for each separate ExcelHandler and instead define the ExcelFileHandler as an abstract service and decorate with the right parameters to get the concrete ExcelHandler Service with the desired functionality, obviously ExcelHandlers with custom logic must be defined seperately, and to create a uniform code base, $mapping will always be injected from the Container in this case.
In your experience, what other paths can I take and which ones yield better results in the long term?
First of all, it seams as you've already put two separate things into one.
Uploading a file and reading it's contents are two separate concerns, which can change separately (like you said, $directory and $mapping can change case-by-case). Thus I would suggest to use separate services for uploading and reading the file.
See Single responsibility principle for more information.
Furthermore, due to very similar reasons, I would not recommend base classes at all - I'd prefer composition over inheritance.
Imagine that you have 2 methods in your base class: upload, which stores file to a local directory, and parse, which reads excel file and maps columns to some data structure.
If you need to store file in a remote storage (for example FTP), you need to override upload method. Let's call this service1.
If you need to parse file differently, for example combining data from 2 sheets, you need to override parse method. Let's call this service2.
If you need to override both of these methods, while still being able to get service1 and service2, you're stuck, as you'll need to copy-and-paste the code. There's no easy way to use already written functionality from (1) and (2).
In comparison, if you have interface with upload method and interface with parse method, you can inject those 2 separate services where you need them as you need them. You can mix any implementations of those already available. All of them are already tested and you do not need to write any code - just to configure the services.
One more thing to mention - there is absolutely no need to create (and name) classes by their usage. Name them by their behaviour. For example, if you have ExcelParser, which takes $mapping as an argument to a constructor, no need to call it UserExcelParser if the code itself has nothing to do with users. If you need to parse data from several sheets, just create SheetAwareExcelParser etc., not ProductExcelParser. This way you can reuse the code. Also correct naming lets understand the code more easily.
In practice, I've seen when function or class is named by it's usage, and then it's just used in another place with no renaming, refactoring etc. These cases are really not what you're looking for.
Service names (in another words concrete objects, not classes), can of course be named by their purpose. You just configure them with any required functionality (single vs separate sheets etc.)
To summarize, I would use 2.1.2 above all other of your given options. I would inject $dir and $mapping via DI in any case, as these do not change in runtime - these are configuration.

trying to use Symfony component and having name space issues

So i am starting a new project and want to use some of the Symfony Components. I have not used name spaces before with PHP, put i am familiar with the concept from my work in java.
i have this simple piece of code and when i run it i get the error:
PHP Fatal error: Class 'Symfony\Component\CssSelector\XPath\Translator' not found in /home/me/scrapes/Symfony/Component/CssSelector/CssSelector/CssSelector.php on line 52
I am thinking it my lack of knowledge of the name space thing.
/home/me/scrapes/Symfony/Component/CssSelector/CssSelector/XPath/Translator.php does exist.
<?php
set_include_path('/home/me/html/inc');
require 'functions.php';
require 'Symfony/Component/DomCrawler/Crawler/Crawler.php';
require 'Symfony/Component/CssSelector/CssSelector/CssSelector.php';
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\CssSelector\CssSelector;
$crawler = new Crawler();
$crawler->addContent('<html><body><p>Hello World!</p></body></html>');
print $crawler->filter('body > p')->text();
curl_close($ch);
require 'cleanup.php';
?>
thanks for any help
I think this is caused because, if you look in the files you required (for example Symfony/Component/DomCrawler/Crawler/Crawler.php) you'll see that those files use their own use statements (to load other classes).
Namespaces
Let's start with the namespaces. A namespace is used to easily create classes with the same name in different packages. Let's say I have a package called Foo and a package called Bar. Both packages contain a Client class that is used to do some client work (one to call the Google Maps API for example and the other to call the Facebook Graph API). Let's also assume neither of the packages uses namespaces.
If I execute the following code:
<?php
require 'Foo/Client.php';
require 'Bar/Client.php';
This is not going to work, because both packages declare a Client class. Oops, how is PHP going to know which Client class to use if you do this?
<?php
$client = new Client();
It's not going to know which Client to use, so it gives up and throws an error.
If you use namespaces (declared using the namespace keyword in PHP at the top of your file, directly below <?php) you can prevent this from happening. The Foo package can create a Client class in the Foo namespace and the Bar package in the Bar namespace. Now we can
actually use both files and create a client:
<?php
require 'Foo/Client.php'
require 'Bar/Client.php'
$fooClient = new Foo\Client();
$barClient = new Bar\Client();
This will work fine.
I think you might have encountered the Foo_Client notation in older PHP libraries. This is an old way to create namespaces before PHP natively supported them.
"But", I hear you say, "it's quite cumbersome to write Foo\Bar\Baz\Client() every time I want to instantiated a class".
It is, and that's where the use keyword comes in. When using the use keyword, I can tell PHP I want to use a specific client and just use the class name, like so:
<?php
require 'Foo/Bar/Baz/Client.php'
use Foo\Bar\Baz\Client;
$client = new Client();
This will work, if you use the use Foo\Bar\Baz\Client statement, because you tell PHP "Okay, I want to use the Client class from the Foo\Bar\Baz namespace to be used when I use the Client class.
Autoloading
Now, what happens if you use a lot of different classes and you seperated them into several files (which you should do). You get a lot of different require and use statements on the top of a file. That's where autoloading comes in.
There has been a spl_register_autoloader function for quite some time in PHP. This function is used by PHP to find out which files to use when you instantiate a class that is not known because you did not require the file. This function is used both when creating a class, or, and this is the key part when you use a class.
And that's what's happening in your code. You don't have an autoloader registered that can translate the use statements in the files you required to actual class declarations.
Great, how do I fix it?
To fix it, I suggest you read up on the PHP-FIG and PSR-4. These people created standards (which you can follow but are not obliged to). To create easy to use libraries, such as the Symfony component. After you've done that, read up on Composer. After you've done this, you can drop the require statements from your code and use Composer to autoload all the classes you need.

What is best way to add additional object classes to my symfony2 controller files?

I'm relatively new to Symfony2, so I'm learning by doing. My controller classes are getting pretty big. I'd like to break it up with functions() or objects->method(). Unfortunately I can't figure out where to put the code. (actually its really simple functions... but I can wrap that in an object...)
--I can't add it to the bottom of my DefaultController.php file. It errors out, and not pretty code to boot, either inside or outside of the { }.
--I can't simply add a new NewObject.php file to the controller directory. That errors out. The error: FatalErrorException: ...NewObject not found.
--I've toyed with manual mods to ../app/autoload.php but that doesn't really make sense for a simple class add to my ./SRC/ bundle. Perhaps I should build a ./src/autoload.php file (similiar to ./vender/autoload.php) but the contents of that file don't make sense to me at all. I simply can't figure out how the AnnotationRegistry Loader works.
Am I missing something? This seems way too hard.. what I want is a wrapped up 'include' so I can use the class in dev and after deployment.
How do I include NewObject.php (and the accompanying $newObject->function() ) in my code?
I'm told I can add a service, yet that seems like outrageous overhead for such a seemingly simple task (again, all I'm trying to do is clean up my very long controller php code...)
thanks in advance for your advice.
So you've got a project structure that looks something like this, right?
project
-- app
-- bin
-- src
-- SomeName
-- SomeBundle
-- Controller
-- Entity
-- Resources
-- ...
-- vendor
-- web
And you're just looking to have some kind of "helper" class that's used throughout your bundle. Is that correct?
If so, then you can really put it wherever you want to inside your src/ directory... Just make sure that the class name matches the file name, and that the path to the file matches the namespace you define at the top of your PHP code.
Sometimes when I do this, I'll create a simple directory under my bundle called "Helper/". Other times, when the application is more complex, I might be a little bit more explicit. But here's what the first case would look like...
First, add your /Helper directory under your bundle, and create the class file:
project
-- app
-- bin
-- src
-- SomeName
-- SomeBundle
-- Controller
-- Entity
-- Helper
-- SomeHelper.php
-- Resources
-- ...
-- vendor
-- web
The contents of SomeHelper.php might look like this:
<?php
namespace SomeName\SomeBundle\Helper;
class SomeHelper
{
public function doSomething()
{
...
}
}
Because your namespace matches the file path, it gets autoloaded, so you don't need to worry about include statements. You can instantiate that class anywhere in your bundle, as long as you include a use statement:
<?php
namespace SomeName\SomeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use SomeName\SomeBundle\Helper\SomeHelper;
class DefaultController extends Controller
{
public function indexAction()
{
...
$helper = new SomeHelper();
$helper->doSomething();
...
}
}
Regarding the usage of services... Yes, that might be overkill, depending on what you're using it for. It's helpful to create services when the class needs to be aware of the application around it. For example, if you're creating a service that emails a User, it might want to access your database through the Doctrine service, or it might want to log the email activity through the Monolog service.
However, if your class doesn't need to know about the application (referred to as the "service container"), for example if it's just used to transfer data, then a helper class is probably more appropriate.

using common methods among multiple classes

I have a couple of class files in C#. I want to write a method that could be used in all the classes. For example, I am trying to write the method that returns the number of rows from the database table, and I need this in multiple times, so thought of writing a single method to share among all the classes. I thought it would be easy with the use of namespace. But when I add namespace in all the class files, it gives error stating "CONTROL NAME is not present in current context". From the internet search I came to the conclusion that I also need to add the namespace in xxx.designer.cs files. Is it correct? I tried to find the designer.cs files but could not, and in one of the solution it was stated that designer.cs file is created during compile time. If so how to add the namespace on designer.cs file.
Thank you!!!
You need to create a static class and this function that classes need to share has to be a static member.
This function can now be called from anywhere.
static class Helper
{
public static string Calculate(int myVariable)
{
//do some common calculation
}
//...
}
If these classes have common data members and you need to share a common function, you can consider using a base class. All common functionality and common data members would go into the base class, and by merit of inheriting that class, all your sub classes would be able to call this function.
Create a Static class and create static member functions into that. You need not to create instance of the class in this case and you can directly call member function using class name.

One file per function...really?

I am relatively new to Flex/ActionScript, but I have been using a pattern of creating one file per function in my util package - with the name of the file being the same as the name of the function. Like if the file was convertTime.as:
package util{
public function convertTime(s:String):Date{
...
}
}
This way I can import the function readily by doing:
import util.convertTime;
...
convertTime(...);
I like this way better than importing a class object and then calling the static methods hanging off of it, like this:
import util.Util;
...
Util.convertTime(...);
But, the more I do this, the more files I'll end up with, and it also seems a bit wasteful/silly to put only one function into a file, especially when the function is small. Is there another alternative to this? Or are these two options the only ones I have?
Update: after some research, I've also posted my own answer below.
Yes, these are your two main options for utility libraries. We actually use both of these approaches for our generic utility functions. For a very small set of functions that we feel should actually be builtins (such as map()), we put one function per file, so that we can use the function directly.
For more obscure/specialized utility functions, we don't want to pollute our global namespace so we make them static functions on a utility class. This way, we're sure that when someone references ArrayUtils.intersect(), we know what library intersect() came from, and what roughly it's for (it intersects two arrays).
I would recommend going with the latter route as much as possible, unless you have a function that a) you use very frequently and b) is really obvious what it does at a glance.
I came across some other alternatives after all and thought I'd share them here.
Alternative 1 - use inheritence
This is probably an obvious answer, but is limited. You would put your static methods into a parent class, inherit them to get them in the subclasses. This would only work with classes. Also, because ActionScript is single inheritence, you can only inherit once.
Alternative 2 - Alias the methods
You still write utility functions as static methods hanging off util classes, but you alias them so you can access them with a shorter name, ex:
import mx.binding.utils.BindingUtils;
var bind:Function = BindingUtils.bindProperty;
Now you can just call
bind(...);
rather than than the lengthy
BindingUtils.bindProperty(...);
You can do this within the class scope and the function scope, but not the package scope - because apparently you can only have one visible attribute inside a package. If you do this in the class scope, you will want to make sure it doesn't conflict with your other class attribute names.
Alternative 3 - use include
As described in this flexonrails blog post you can use include to simulate a mixin in ActionScript. An include is different from an import in that all it's doing is copying the entirety of the file you are including from and paste it into the place you are including it at. So, it has completely no handling of namespace issues, you can not reference its full path name afterwards like you can with imports, if you have conflicting names, you are on your own with this. Also unlike import, it creates different copies of the same code. But what you can do with this is put any number of functions in a file, and include them into class or function scope in another file. Ex:
// util/time_utils.as
function convertTime(..){
...
}
function convertDate(..){
...
}
To include:
include 'util/time_util.as'; // this is always a relative path
...
convertTime(...);
# an0nym0usc0ward
OOP is simply the method of consolidating like functions or properties into an object that can be imported and used. It is nothing more that a form of organization for your code, ALL code executes procedurally in the processor in the end, OOP is just organization of sources. What he is doing here may not be OOP as you learn from a book, but it does the exact same thing in the end, and should be treated with the same respect.
Anyone that truly understands OOP wouldn't be naive enough to think that the approved and documented form of OOP is the only possible way to object orient your code.
EDIT: This was supposed to be a comment response to an0nym0usc0ward's rude comment telling him to learn OOP. But I guess I typed it in the wrong box :)

Resources