Include php files joomla

Содержание
  1. The Joomla! Forum™
  2. How include my additional php-file into blog.php template?
  3. How include my additional php-file into blog.php template?
  4. Re: How include my additional php-file into blog.php template?
  5. Re: How include my additional php-file into blog.php template?
  6. Re: How include my additional php-file into blog.php template?
  7. Re: How include my additional php-file into blog.php template?
  8. Re: How include my additional php-file into blog.php template?
  9. Re: How include my additional php-file into blog.php template?
  10. Re: How include my additional php-file into blog.php template?
  11. Re: How include my additional php-file into blog.php template?
  12. Re: How include my additional php-file into blog.php template?
  13. Re: How include my additional php-file into blog.php template?
  14. Re: How include my additional php-file into blog.php template?
  15. The Joomla! Forum™
  16. How to include PHP and javascript code in articles ?
  17. How to include PHP and javascript code in articles ?
  18. Re: How to include PHP and javascript code in articles ?
  19. Re: How to include PHP and javascript code in articles ?
  20. Re: How to include PHP and javascript code in articles ?
  21. Re: How to include PHP and javascript code in articles ?
  22. Re: How to include PHP and javascript code in articles ?
  23. Re: How to include PHP and javascript code in articles ?
  24. Re: How to include PHP and javascript code in articles ?
  25. Re: How to include PHP and javascript code in articles ?
  26. Re: How to include PHP and javascript code in articles ?
  27. Re: How to include PHP and javascript code in articles ?
  28. Re: How to include PHP and javascript code in articles ?
  29. Re: How to include PHP and javascript code in articles ?
  30. Re: How to include PHP and javascript code in articles ?
  31. Re: How to include PHP and javascript code in articles ?
  32. Как вставить php код. Конструкция включений в PHP include
  33. Как вставить php код в joomla (2, 3)
  34. Joomla! Developer Network™
  35. PHP Code
  36. About
  37. Coding Standards
  38. Client Side Syntax Style Guides
  39. Appendices
  40. General
  41. Including Code
  42. E_STRICT Compatible PHP Code
  43. Global Variables
  44. Error Surpression
  45. Control Structures (General Code)
  46. An if-else Example
  47. A do-while Example
  48. A for Example
  49. A foreach Example
  50. A while Example
  51. A switch example
  52. A try catch example
  53. Mixed language usage (e.g. at the layout files)
  54. Example Control Structures
  55. References
  56. Concatenation Spacing
  57. Arrays
  58. Code Commenting
  59. Comment Docblocks
  60. Function Calls
  61. Function Definitions
  62. Closures / Anonymous functions
  63. Class Definitions
  64. Class Property DocBlocks
  65. Class Method DocBlocks
  66. Class Definition Example
  67. Naming Conventions
  68. Classes
  69. Functions and Methods
  70. Namespaces
  71. Constants
  72. Regular Variables and Class Properties
  73. Exception Handling
  74. Logic Exceptions
  75. Runtime Exceptions
  76. Documenting exceptions
  77. SQL Queries

The Joomla! Forum™

How include my additional php-file into blog.php template?

How include my additional php-file into blog.php template?

Post by ice99 » Tue Jul 19, 2016 6:43 am

For example i have php file in
templates/MyTemplate/includes/MyPhp.php

I want to include it inside my blog.php template.
(I want include it into template, not into the article, so Sourceer useless for it)

I’ve read that Joomla don’t recommend using include_once (https://docs.joomla.org/Security_Checkl . rver_Setup) and recommend use allow_url_fopen, but i don’t find any example.

Re: How include my additional php-file into blog.php template?

Post by Per Yngve Berg » Tue Jul 19, 2016 7:04 am

Re: How include my additional php-file into blog.php template?

Post by ice99 » Tue Jul 19, 2016 7:18 am

This answer may be normal in «Joomla Developers forum», but not in «Novice forum»

Write a plugin for simpliest operation?

Bye the way following construction works fine on php 7.0.4

Re: How include my additional php-file into blog.php template?

Post by sovainfo » Tue Jul 19, 2016 8:17 am

This answer may be normal in «Joomla Developers forum», but not in «Novice forum»

Write a plugin for simpliest operation?

Re: How include my additional php-file into blog.php template?

Post by ice99 » Tue Jul 19, 2016 4:13 pm

Re: How include my additional php-file into blog.php template?

Post by RedEye » Fri Jul 22, 2016 2:28 pm

Re: How include my additional php-file into blog.php template?

Post by sovainfo » Fri Jul 22, 2016 3:49 pm

OMG, if you don’t even understand you should write a plugin to realize what is done by the MyPhp.php, I give up!

And yes it requires you to specify the correct path to the file. Removal of the extra ‘/’ or the one before includes would have worked fine.

Re: How include my additional php-file into blog.php template?

Post by RedEye » Fri Jul 22, 2016 5:28 pm

Re: How include my additional php-file into blog.php template?

Post by sovainfo » Fri Jul 22, 2016 5:54 pm

Can’t believe such a stupid remark! We don’t even know what the functionality he wants to add! How can you judge a plugin to be an overkill, when you don’t know the desired functionality. Using Joomla you should think about functionality. But you just proved there still too many of those php cowboys that don’t understand software development. The technical solution requires a functional solution first.

Evidently that is beyond the two of you! Indeed giving up, glad there is an ignore list!

Re: How include my additional php-file into blog.php template?

Post by RedEye » Fri Jul 22, 2016 6:23 pm

Re: How include my additional php-file into blog.php template?

Post by sovainfo » Fri Jul 22, 2016 6:49 pm

Re: How include my additional php-file into blog.php template?

Post by ice99 » Fri Jul 29, 2016 10:49 am

Источник

The Joomla! Forum™

How to include PHP and javascript code in articles ?

How to include PHP and javascript code in articles ?

Post by arvin88 » Sat Mar 15, 2008 9:12 am

Can some one answer these questions ?

1) How to include PHP and JAVASCRIPT code in articles , so i can embed registration form in articles. I am creating a college cultural website and i need to embed registration form for each event .

2) How to add a navigation bar inside a article ? This is how i want the look to be . I am attaching the images

Please help me, i need your help . Very Urgent !

Re: How to include PHP and javascript code in articles ?

Post by MarHaj » Sun Mar 16, 2008 6:13 pm

Re: How to include PHP and javascript code in articles ?

Post by allan27 » Fri Mar 21, 2008 3:10 am

I’ve been using Joomla for the past 2 weeks, I’m not totally familiar with it, and I’m facing the same problem like the thread starter. So lucky there’s Jumi.

Im very new to the Jumi,

I have problem to understand how it works.

i have read through the tutorial site, the demo shows that

Let’s say i put my php file at c:\wamp\www\Prototype\jumies\hello_args.php

so. how am i going to replace my path at the [somepath/hello_args.php]?

i have tried, [..Prototype/jumies/hellow_args.php] but it’s not working.

Would you enlighten me pls?

Re: How to include PHP and javascript code in articles ?

Post by MarHaj » Fri Mar 21, 2008 10:41 am

Читайте также:  Xbox для windows 10 ошибка 0x406

Re: How to include PHP and javascript code in articles ?

Post by allan27 » Mon Apr 07, 2008 10:01 am

Re: How to include PHP and javascript code in articles ?

Post by MarHaj » Mon Apr 07, 2008 12:36 pm

Re: How to include PHP and javascript code in articles ?

Post by davidllovi » Sun Nov 02, 2008 10:36 am

Hi,
thanks for all the help provided. I would like to check if I am following the proper way with including a .js file.
I have a library file in javascript I would like to use. I have done the following:
— installed jumi
— I have uploaded my file using docman. I could also use the image uploader. Is that a good policy?
— enabled the JCE to include javascript
— and then included:

And it works!
Is there anything I could improve?
Thanks!!

Re: How to include PHP and javascript code in articles ?

Post by MarHaj » Sun Nov 02, 2008 10:56 am

Re: How to include PHP and javascript code in articles ?

Post by davidllovi » Sun Nov 02, 2008 12:30 pm

Re: How to include PHP and javascript code in articles ?

Post by lguilherme » Wed May 06, 2009 4:16 am

Re: How to include PHP and javascript code in articles ?

Post by MarHaj » Wed May 06, 2009 7:09 am

Lguilherme,
I wish I could help.
You have a rather strict need: by tomorrow.
I am afraid I am busy right now and will be available just few hours these two days.
Nevertheless we could try it.

Could you be more specific with «blocking». Or better: send me an email (admin at vedeme.cz) with your code attached. I will have a look at it and let you know (rem — I am leaving now and will be back in 12 hours).

Re: How to include PHP and javascript code in articles ?

Post by nayyerkamran » Wed Jul 08, 2009 4:15 pm

I tried to use jumi plugin and used following code in my article.

and when I browse to article it simple print out the same line. As far pathing is concern I can access this form_handler.php page using following URL

Can you give me some suggestion what I may be missing or doing wrong.

Re: How to include PHP and javascript code in articles ?

Post by MarHaj » Thu Jul 09, 2009 7:30 am

Re: How to include PHP and javascript code in articles ?

Post by nayyerkamran » Thu Jul 09, 2009 11:26 am

Thanks for your answer. The problem was not with template; it was because of an invisible character between »

Thanks for your help.

Re: How to include PHP and javascript code in articles ?

Post by dynamyt100 » Fri Nov 13, 2009 5:12 am

Hi. I read these posts and decided to install Jumi for v1.5

Источник

Как вставить php код. Конструкция включений в PHP include

Конструкция include предназначена для включения файлов в код сценария PHP во время исполнения сценария PHP.

В отличие от конструкции require конструкция include позволяет включать файлы в код PHP скрипта во времявыполнения сценария. Синтаксис конструкции include выглядит следующим образом:

Поясним принципиальную разницу между конструкциями require и include на конкретном практическом примере. Создадим 10 файлов с именами 1.txt, 2.txt и так далее до 10.txt, содержимое этих файлов — просто десятичные цифры 1, 2 . … 10 (по одной цифре в каждом файле). Создадим такой сценарий PHP:

В результате мы получим вывод, состоящий из 10 цифр: «12345678910». Из этого мы можем слелать вывод, что каждый из файлов был включен по одному разу прямо во время выполнения цикла! Если мы поставим теперь вместоinclude require, то сценарий сгенерирует критическую ошибку (fatal error). Сравните результат.

PHP преобразует сценарий во внутреннее представление, анализируя строки сценария по очереди, пока не доходит до конструкции include. Дойдя до include, PHP прекращает транслировать сценарий и переключается на указанный в include файл. Таким образом из-за подобного поведения транслятора, быстродействие сценария снижается, особенно при большом колличестве включаемых с помощью include файлов. С require таких проблем нет, поскольку файлы с помощью require включаются до выполнения сценария, то есть на момент трансляции файл уже включен в сценарий.

Таким образом, целесообразнее использовать конструкцию require там, где не требуется динамическое включение файлов в сценарий, а конструкцию include использовать только с целью динамического включения файлов в код PHP скрипта.

Конструкция include поддерживает включения удаленных файлов (начиная с версии PHP 4.3.0). Например:

! Конструкция include позволяет включать удаленные файлы, если такая возможность включена в конфигурационном файле PHP.

Включения удаленных файлов

PHP позволяет работать с объектами URL, как с обычными файлами. Упаковщики, доступные по умолчанию, служат для работы с удаленными файлами с использованием протокола ftp или http.

Если «URL fopen-оболочки» включены в PHP (как в конфигурации по умолчанию), вы можете специфицировать файл, подключаемый с использованием URL (через HTTP), вместо локального пути. Если целевой сервер интерпретирует целевой файл как PHP-код, переменные могут передаваться в подключаемый файл с использованием URL-строки запроса, как в HTTP GET. Строго говоря, это не то же самое, что подключение файла и наследование им области видимости переменных родительского файла; ведь скрипт работает на удалённом сервере, а результат затем подключается в локальный скрипт.

Для того, чтобы удаленное включение файлов было доступно, необходимо в конфигурационном файле (php.ini)установить allow_url_fopen=1.

Обратите внимание: Версии PHP для Windows до PHP 4.3.0 не поддерживают возможность использования удаленных файлов этой функцией даже в том случае, если опция allow_url_fopen включена.

Как вставить php код в joomla (2, 3)

Всем пользователям, кто знаком с joomla известно, что вставить php в joomla довольно проблематично. Как только доходит дело до сохранения материала, редактор joomla просто вырезает или экранирует этот код и в результате вставленный код PHP, java, и т.д. не работает.

В joomla версии 2.5, 3 эта проблема решается путем выставления некоторых настроек в «общие настройки — фильтры текста.

Конечно можно поколдовать в фильтрах текста в вашем WYSIWYG редакторе, но а что если и это тоже не помогает ? Для вставки кода в joomla поможет установка бесплатного плагина Sourcerer.

С его помощью можно легко вставлять любой код в материал или модуль, причем в любом месте.
При установке плагина, в редакторе появляется дополнительная кнопка «вставить код»:

Плагин обрабатывает все свои теги в коде вашего сайта. Вы можете вставлять произвольные скрипты и код html, javascript, css и php код в joomla (включая, собственные теги этих языков) между тегами Sourcerer:

Плагин считывает весь код между своими тегами и отделяет его от html-разметки страницы. Так что Sourcerer позволяет размещать PHP и любой HTML код стиля (включая CSS и JavaScript) прямо в ваш контент! Не только в ваших статьях, но и в секциях, категориях, модулях, компонентах, мета-тегах, и т.д. Теперь вы можете просто разместить оригинальные коды прямо в редакторе WYSIWYG.Единственное, что вам нужно сделать, это окружить код с тегами Sourcerer. Проще простого!

Читайте также:  Как переносить картридж для заправки

На этом все — надеюсь материал был для Вас полезен.

Источник

Joomla! Developer Network™

PHP Code

About

Coding Standards

Client Side Syntax Style Guides

Appendices

The Joomla! CMS switched in Version 4.2.0 from its own coding standard to the PSR-12 (and later to PER Coding Style) coding standard.
This document applies to Joomla! to delimit PHP code, not the shorthand. This is the most portable way to include PHP code on differing operating systems and setups.

For files that contain only PHP code, the closing tag ( ?> ) should not be included. It is not required by PHP. Leaving this out prevents trailing white space from being accidentally injected into the output that can introduce errors in the Joomla session (see the PHP manual on Instruction separation).

Files should always end with a blank new line.

General

PHP keywords MUST be in lower case.
The PHP constants true , false , and null MUST be in lower case.

Including Code

Anywhere you are unconditionally including a file, use require_once . Anywhere you are conditionally including a file (for example, factory methods), use include_once . Either of these will ensure that files are included only once. They share the same file list, so you don’t need to worry about mixing them. A file included with require_once will not be included again by include_once .

include_once and require_once are PHP language statements, not functions. The correct formatting is:

require_once JPATH_COMPONENT . ‘/helpers/helper.php’;

You should not enclose the filename in parentheses.

E_STRICT Compatible PHP Code

As of Joomla version 1.6 and for all versions of the Joomla Platform, adhering to object oriented programming practice as supported by PHP 5.3+ is required. Joomla is committed to progressively making the source code E_STRICT.

Global Variables

Global variables should not be used. Use static class properties or constants instead of globals, following OOP and factory patterns.

Error Surpression

The use of the @ for Error Surpression should be avoided and limited to use when no other approach or workaround is available.

Control Structures (General Code)

For all control structures there is a space between the keyword and an opening parenthesis, then no space either after the opening parenthesis or before the closing bracket. This is done to distinguish control keywords from function names. All control structures must contain their logic within braces.

For all all control structures, such as if , else , do , for , foreach , try , catch , switch and while , both the keyword starts a newline and the opening and closing braces are each put on a new line.

Exclamation mark ! , the logical operator not used in a condition, should not have spaces before or after the exclamation mark as shown in the examples.

An if-else Example

If a control structure goes over multiple lines, all lines must be indented with one tab and the closing brace must go on the same line as the last parameter.

A do-while Example

A for Example

A foreach Example

A while Example

A switch example

When using a switch statement, the case keywords are indented. The break statement starts on a newline assuming the indent of the code within the case.

A try catch example

Mixed language usage (e.g. at the layout files)

For layout files and all files where we use a mix of PHP and HTML (all PHP files in the view/tmpl and layout folder) we additionally wrap every line into a block and use the alternative syntax for control structures. This should make the code easier to read and make it easier to move blocks around without creating fatal errors due to missing tags.

Example Control Structures

An if-else Example

References

When using references, there should be a space before the reference operator and no space between it and the function or variable name.

In PHP 5, reference operators are not required for objects. All objects are handled by reference.

Concatenation Spacing

There should always be a space before and after the concatenation operator (‘.’). For example:

If the concatenation operator is the first or last character on a line, both spaces are not required. For example:

Arrays

Assignments (the => operator) in arrays may be aligned with spaces. When splitting array definitions onto several lines, the last value should also have a trailing comma. This is valid PHP syntax and helps to keep code diffs minimal. Joomla 3 prefers array() to be backward compatible to 5.3.10 and Joomla 4.0.0 onwards should use the short array syntax [] by default. (Short array syntax was introduced in PHP 5.4.)

Code Commenting

Inline comments to explain code follow the convention for C ( /* … */ ) and C++ single line ( // . ) comments. C-style blocks are generally restricted to documentation headers for files, classes and functions. The C++ style is generally used for making code notes. Code notes are strongly encouraged to help other people, including your future-self, follow the purpose of the code. Always provide notes where the code is performing particularly complex operations.

Perl/shell style comments ( # ) are not permitted in PHP files.

Blocks of code may, of course, be commented out for debugging purposes using any appropriate format, but should be removed before submitting patches for contribution back to the core code.

For example, do not include feature submissions like:

More details on inline code comments can be found in the chapter on Inline Code Comments.

Comment Docblocks

Documentation headers for PHP and Javascript code in files, classes, class properties, methods and functions, called the docblocks, follow a convention similar to JavaDoc or phpDOC.

These «DocBlocks» borrow from the PEAR standard but have some variations specific for Joomla and the Joomla Platform.

More details on DocBlocks comments can be found in the chapter on DocBlocks Comments.

Function Calls

Functions should be called with no spaces between the function name and the opening parenthesis, and no space between this and the first parameter; a space after the comma between each parameter (if they are present), and no space between the last parameter and the closing parenthesis. There should be space before and exactly one space after the equals sign. Tab alignment over multiple lines is permitted.

Function Definitions

Function definitions start on a new line with no spaces between the function name and the opening parenthesis. Additionally, the opening and closing braces are also placed on new lines. An empty line should precede lines specifying the return value.

Function definitions must include a documentation comment in accordance with the Commenting section of this document. More details on DocBlocks Function comments can be found in the chapter on DocBlocks Comments.

If a function definition goes over multiple lines, all lines must be indented with one tab and the closing brace must go on the same line as the last parameter.

Читайте также:  Astra linux на телефоне

Closures / Anonymous functions

Closures/Anonymous functions should have a space between the Closure’s/Anonymous function’s name and the opening parenthesis. Method signatures don’t have the space.

Class Definitions

Class definitions start on a new line and the opening and closing braces are also placed on new lines. Class methods must follow the guidelines for Function Definitions. Properties and methods must follow OOP standards and be declared appropriately (using public, protected, private and static as applicable).

Class definitions, properties and methods must each be provided with a DocBlock in accordance with the following sections.

More details on DocBlocks Class comments can be found in the chapter on DocBlocks Comments.

Class Property DocBlocks

More details on Class Property DocBlocks can be found in the chapter on DocBlocks Comments.

Class Method DocBlocks

The DocBlock for class methods follows the same convention as for PHP functions.

More details on DocBlocks Class Method comments can be found in the chapter on DocBlocks Comments.

Class Definition Example

Naming Conventions

Classes

Classes should be given descriptive names. Avoid using abbreviations where possible. Class names should always begin with an uppercase letter and be written in CamelCase even if using traditionally uppercase acronyms (such as XML, HTML). One exception is for Joomla Platform classes which must begin with an uppercase ‘J’ with the next letter also being uppercase.

Functions and Methods

Functions and methods should be named using the «studly caps» style (also referred to as «bumpy case» or «camel caps»). The initial letter of the name is lowercase, and each letter that starts a new «word» is capitalized. Function in the Joomla framework must begin with a lowercase ‘j’.

Private class members (meaning class members that are intended to be used only from within the same class in which they are declared) are preceded by a single underscore. Properties are to be written in underscore format (that is, logical words separated by underscores) and should be all lowercase.

Namespaces

Namespaces are formatted according to this flow. First there is the file docblock followed by the namespace the file lives in. When required, the namespace is followed by the defined check. Lastly, the imported classes using the use keyword. All namespace imports must be alphabetically ordered.

Constants

Constants should always be all-uppercase, with underscores to separate words. Prefix constant names with the uppercase name of the class/package they are used in. For example, the constants used by the JError class all begin with JERROR_ .

Regular Variables and Class Properties

Regular variables, follow the same conventions as function.

Class variables should be set to null or some other appropriate default value.

Exception Handling

Exceptions should be used for error handling.

The following sections outline how to semantically use SPL exceptions.

Logic Exceptions

The LogicException is thrown when there is an explicit problem with the way the API is being used. For example, if a dependency has failed (you try to operate on an object that has not been loaded yet).

The following child classes can also be used in appropriate situations:

BadFunctionCallException

This exception can be thrown if a callback refers to an undefined function or if some arguments are missing. For example if is_callable() , or similar, fails on a function.

BadMethodCallException

This exception can be thrown if a callback refers to an undefined method or if some arguments are missing. For example is_callable() , or similar, fails on a class method. Another example might be if arguments passed to a magic call method are missing.

InvalidArgumentException

This exception can be thrown if there is invalid input.

DomainException

This exception is similar to the InvalidArgumentException but can be thrown if a value does not adhere to a defined valid data domain. For example trying to load a database driver of type «mongodb» but that driver is not available in the API.

LengthException

This exception can be thrown is a length check on an argument fails. For example a file signature was not a specific number of characters.

OutOfRangeException

This exception has few practical applications but can be thrown when an illegal index was requested.

Runtime Exceptions

The RuntimeException is thrown when some sort of external entity or environment causes a problem that is beyond your control providing the input is valid. This exception is the default case for when the cause of an error can’t explicitly be determined. For example you tried to connect to a database but the database was not available (server down, etc). Another example might be if an SQL query failed.

UnexpectedValueException

This type of exception should be used when an unexpected result is encountered. For example a function call returned a string when a boolean was expected.

OutOfBoundsException

This exception has few practical applications but may be thrown if a value is not a valid key.

OverflowException

This exception has few practical applications but may be thrown when you add an element into a full container.

RangeException

This exception has few practical applications but may be thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of DomainException.

UnderflowException

This exception has few practical applications but may thrown when you try to remove an element of an empty container.

Documenting exceptions

Each function or method must annotate the type of exception that it throws using an @throws tag and any downstream exceptions types that are thrown. Each type of exception need only be annotated once. No description is necessary.

SQL Queries

SQL keywords are to be written in uppercase, while all other identifiers (with the exception of quoted text obviously) is to be in lowercase.

All table names should use the #__ prefix to access Joomla content and allow for the user defined database prefix to be applied. Queries should also use the JDatabaseQuery API. Tables should never have a static prefix such as jos_ .

To query our data source we can call a number of JDatabaseQuery methods; these methods encapsulate the data source’s query language (in most cases SQL), hiding query-specific syntax from the developer and increasing the portability of the developer’s source code.

Use Query chaining to connect a number of query methods, one after the other, with each method returning an object that can support the next method, This improves readability and simplifies the resulting code. Since the Joomla Framework was introduced «query chaining» is now the recommended method for building database queries.

Table names and table column names should always be enclosed in the quoteName() method to escape the table name and table columns.
Field values checked in a query should always be enclosed in the quote() method to escape the value before passing it to the database. Integer field values checked in a query should also be type cast to (int) .

Источник

Поделиться с друзьями
КомпСовет
Adblock
detector