PrestaShop + Docker

GitHub Docker Prestashop

DockerHub Prestashop
https://hub.docker.com/r/prestashop/prestashop/

Docker-Composeファイルによるコンテナ作成時の環境設定は以下の通り。

  prestashop-fpm:
    container_name: prestashop-fpm
    image: prestashop/prestashop:1.7-7.2-fpm    
    tty: true
    expose: 
      - "9000"
    environment:
      - PS_DEV_MODE=true
      - DB_SERVER=localhost
      - DB_USER=user
      - DB_PASSWD=passowrd
      - DB_NAME=store
      - PS_INSTALL_AUTO=1
      - PS_DOMAIN=www.testsite.com
      - PS_LANGUAGE=ja
      - PS_COUNTRY=JP
      - PS_FOLDER_ADMIN=your_admin
      - PS_ENABLE_SSL=1
      - ADMIN_MAIL=test001@gmail.com
      - ADMIN_PASSWD=adminpassword
      - TZ=Asia/Tokyo

:warning:

注1) PrestaShopを指定ドメインのサブディレクトにインストールする場合は、PrestaShopデータベースのテーブル “ps_shop_url”“physical_uri”“/sub_directory/” を追加すること。 これをしないと Nginx 502 error が発生します。

注2)Installディレクトリは自動削除されるため、途中手動で削除しないこと。

ストア設定

Shop Parameters ---> Contact ---> Stores でストアの名称、場所、メールなどの設定・追加・変更が出来ます。

pecl memcacheのインストール

Prestashopのキャッシュを有効化するため、php7.2-fpmコンテナにPECLによりPHP拡張機能memcacheを追加。

PECL
https://pecl.php.net/

php7.2-fpmコンテナ内で以下のpeclコマンドによりインストール

# pecl install memcache

peclコマンド一覧

# pecl
Commands:
build                  Build an Extension From C Source
bundle                 Unpacks a Pecl Package
channel-add            Add a Channel
channel-alias          Specify an alias to a channel name
channel-delete         Remove a Channel From the List
channel-discover       Initialize a Channel from its server
channel-info           Retrieve Information on a Channel
channel-login          Connects and authenticates to remote channel server
channel-logout         Logs out from the remote channel server
channel-update         Update an Existing Channel
clear-cache            Clear Web Services Cache
config-create          Create a Default configuration file
config-get             Show One Setting
config-help            Show Information About Setting
config-set             Change Setting
config-show            Show All Settings
convert                Convert a package.xml 1.0 to package.xml 2.0 format
cvsdiff                Run a "cvs diff" for all files in a package
cvstag                 Set CVS Release Tag
download               Download Package
download-all           Downloads each available package from the default channel
info                   Display information about a package
install                Install Package
list                   List Installed Packages In The Default Channel
list-all               List All Packages
list-channels          List Available Channels
list-files             List Files In Installed Package
list-upgrades          List Available Upgrades
login                  Connects and authenticates to remote server [Deprecated in favor of channel-login]
logout                 Logs out from the remote server [Deprecated in favor of channel-logout]
makerpm                Builds an RPM spec file from a PEAR package
package                Build Package
package-dependencies   Show package dependencies
package-validate       Validate Package Consistency
pickle                 Build PECL Package
remote-info            Information About Remote Packages
remote-list            List Remote Packages
run-scripts            Run Post-Install Scripts bundled with a package
run-tests              Run Regression Tests
search                 Search remote package database
shell-test             Shell Script Test
sign                   Sign a package distribution file
svntag                 Set SVN Release Tag
uninstall              Un-install Package
update-channels        Update the Channel List
upgrade                Upgrade Package
upgrade-all            Upgrade All Packages [Deprecated in favor of calling upgrade with no parameters]
Usage: pecl [options] command [command-options] <parameters>
Type "pecl help options" to list all options.
Type "pecl help shortcuts" to list all command shortcuts.
Type "pecl help version" or "pecl version" to list version information.
Type "pecl help <command>" to get the help for the specified command.

キャッシュの有効化

MBOモジュール 503 エラー

モジュールセレクション:modules/addons/modules/catalog/selection、
テーマ一覧:modules/addons/themes/catalog
"Recommended Modules and Services"ボタンなどでの表示エラー

MBO_Error

<原因1:doctrineマッピングエラー>

Entities Mapping

Class Mapping errors
PrestaShopBundle\Entity\Tab * The association PrestaShopBundle\Entity\Tab#tabLangs refers to the owning side field PrestaShopBundle\Entity\TabLang#tab which does not exist.

<対策:以下ファイルの該当箇所を修正>

# nano src/PrestaShopBundle/Entity/TabLang.php

private $id —> private $tab へ修正

class TabLang
{
    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="PrestaShopBundle\Entity\Tab", inversedBy="tabLangs")
     * @ORM\JoinColumn(name="id_tab", referencedColumnName="id_tab", nullable=false)
     */
    private $tab;
.......
.......

<2021/06/11 更新>エラー対応

/modules/ps_mbo/src/ExternalContentProvider/ExternalContentProvider.php
0.6 —> 20へ変更。

class ExternalContentProvider implements ExternalContentProviderInterface
{
    .....

    const TIMEOUT_SECONDS = 20;

    .....

Symfonyデバックモードによる以下メッセージの非表示対応

Enabling the “sensio_framework_extra.router.annotations” configuration is deprecated since version 5.2. Set it to false and use the “Symfony\Component\Routing\Annotation\Route” annotation from Symfony itself

コンテナ内で設定ファイルconfig.ymlに無効化するセクションを追加

# nano app/config/config.yml
sensio_framework_extra:
    router:
         annotations: false

Webhooks vs APIs(application programming interfaces) — What’s The Difference?

Stripe(支払いサービス)を例に、APIWebhookの違いを説明

データプル型のAPIに対し、Webhookはデータプッシュ型
apis-vs-webhooks

多くのイベント発生時や、より詳細なデータを取得する場合などにはAPIが有利。

api-poll-vs-webhook-push

Stripe

Prestashop Stripe モジュール
https://addons.prestashop.com/en/payment-card-wallet/24922-stripe-official-sca-ready.html

コマンドによるキャッシュクリア

コンテナ内で以下フォルダ削除

$ docker exec -ti prestashop-fpm bash
# rm -r var/cache/prod

または、 bin/console コマンドによりキャッシュクリア(--env=prod or --env=dev)

# bin/console cache:clear --env=prod

bin/console コマンド一覧

# bin/console list
Symfony 3.4.49 (kernel: app, env: dev, debug: true)

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -e, --env=ENV         The Environment name. [default: "dev"]
      --no-debug        Switches off debug mode.
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  about                                               Displays information about the current project
  help                                                Displays help for a command
  list                                                Lists commands
 assets
  assets:install                                      Installs bundles web assets under a public directory
 cache
  cache:clear                                         Clears the cache
  cache:pool:clear                                    Clears cache pools
  cache:pool:prune                                    Prunes cache pools
  cache:warmup                                        Warms up an empty cache
 config
  config:dump-reference                               Dumps the default configuration for an extension
 debug
  debug:autowiring                                    Lists classes/interfaces you can use for autowiring
  debug:config                                        Dumps the current configuration for an extension
  debug:container                                     Displays current services for an application
  debug:event-dispatcher                              Displays configured listeners for an application
  debug:form                                          Displays form type information
  debug:router                                        Displays current routes for an application
  debug:swiftmailer                                   Displays current mailers for an application
  debug:tactician                                     
  debug:translation                                   Displays translation messages information
  debug:twig                                          Shows a list of twig functions, filters, globals and tests
 doctrine
  doctrine:cache:clear-collection-region              Clear a second-level cache collection region
  doctrine:cache:clear-entity-region                  Clear a second-level cache entity region
  doctrine:cache:clear-metadata                       Clears all metadata cache for an entity manager
  doctrine:cache:clear-query                          Clears all query cache for an entity manager
  doctrine:cache:clear-query-region                   Clear a second-level cache query region
  doctrine:cache:clear-result                         Clears result cache for an entity manager
  doctrine:cache:contains                             Check if a cache entry exists
  doctrine:cache:delete                               Delete a cache entry
  doctrine:cache:flush                                [doctrine:cache:clear] Flush a given cache
  doctrine:cache:stats                                Get stats on a given cache provider
  doctrine:database:create                            Creates the configured database
  doctrine:database:drop                              Drops the configured database
  doctrine:database:import                            Import SQL file(s) directly to Database.
  doctrine:ensure-production-settings                 Verify that Doctrine is properly configured for a production environment
  doctrine:generate:entities                          [generate:doctrine:entities] Generates entity classes and method stubs from your mapping information
  doctrine:mapping:convert                            [orm:convert:mapping] Convert mapping information between supported formats
  doctrine:mapping:import                             Imports mapping information from an existing database
  doctrine:mapping:info                               
  doctrine:query:dql                                  Executes arbitrary DQL directly from the command line
  doctrine:query:sql                                  Executes arbitrary SQL directly from the command line.
  doctrine:schema:create                              Executes (or dumps) the SQL needed to generate the database schema
  doctrine:schema:drop                                Executes (or dumps) the SQL needed to drop the current database schema
  doctrine:schema:update                              Executes (or dumps) the SQL needed to update the database schema to match the current mapping metadata
  doctrine:schema:validate                            Validate the mapping files
 fos
  fos:js-routing:debug                                Displays currently exposed routes for an application
  fos:js-routing:dump                                 Dumps exposed routes to the filesystem
 lint
  lint:twig                                           Lints a template and outputs encountered errors
  lint:xliff                                          Lints a XLIFF file and outputs encountered errors
  lint:yaml                                           Lints a file and outputs encountered errors
 prestashop
  prestashop:licenses:update                          Rewrite your licenses to be up-to-date
  prestashop:linter:legacy-link                       Checks if _legacy_link is configured in BackOffice routes
  prestashop:linter:naming-convention                 Checks if Back Office routes and controllers follow naming convention.
  prestashop:linter:security-annotation               Checks if Back Office route controllers has configured Security annotations.
  prestashop:list:commands-and-queries                Lists available CQRS commands and queries
  prestashop:mail:generate                            Generate mail templates for a specified theme
  prestashop:module                                   Manage your modules via command line
  prestashop:schema:update-without-foreign            Update the database
  prestashop:taxes:update-eu-tax-rule-groups          Update EU Tax rule groups
  prestashop:theme:enable                             Manage your themes via command line
  prestashop:theme:export                             Create zip to distribute theme with its dependencies
  prestashop:translation:find-duplicates              Find duplicates of your translations
  prestashop:update:configuration-file-hooks-listing  Appends configuration file hooks list
  prestashop:update:sql-upgrade-file-hooks-listing    Adds sql to sql upgrade file which contains hook insert opeartion
 router
  router:match                                        Helps debug routes by simulating a path info match
 security
  security:check                                      Checks security issues in your project dependencies
  security:encode-password                            Encodes a password.
 server
  server:log                                          Starts a log server that displays logs in real time
  server:run                                          Runs a local web server
  server:start                                        Starts a local web server in the background
  server:status                                       Outputs the status of the local web server
  server:stop                                         Stops the local web server that was started with the server:start command
 swiftmailer
  swiftmailer:email:send                              Send simple email message
  swiftmailer:spool:send                              Sends emails from the spool
 translation
  translation:update                                  Updates the translation file

テンプレートのカスタマイズ

テーマのテンプレートディレクトリ
themes/classic/templates/_partials

テンプレート編集後は管理画面から
Advanced Parameters ---> Performance からキャッシュをクリアすることで変更内容が反映されます。

ex) Footerの編集

# nano themes/classic/templates/_partials/footer.tpl
<a href="https://www.prestashop.com" target="_blank" rel="noopener noreferrer nofollow">
              {l s='%copyright% %year% - Ecommerce software by %prestashop%' sprintf=['%prestashop%' => 'PrestaShop™', '%year%' => 'Y'|date, '%copyright%' => '©'] d='Shop.Theme.Global'}
            </a>

通貨レートアップデート

モジュールによる通貨レートのアップデートではなく、ホストマシンのクローンジョブで対応。以下のコマンドをクローンジョブに追加。

# php /var/www/html/admin/cron_currency_rates.php secure_key=displayed_the_correct_secure_key

$secureKey は以下ファイルの一部を変更(echoによる確認)し抽出。抽出後削除すること。

/var/www/html/admin/cron_currency_rates.php

if (isset($_GET['secure_key'])) {
    $secureKey = md5(_COOKIE_KEY_.Configuration::get('PS_SHOP_NAME'));
    echo $secureKey;
    if (!empty($secureKey) && $secureKey === $_GET['secure_key']) {
        $shop_ids = Shop::getCompleteListOfShopsID();
        foreach ($shop_ids as $shop_id) {
            Shop::setContext(Shop::CONTEXT_SHOP, (int)$shop_id);
            Currency::refreshCurrencies();
        }
    }
}

secure_key=xxxxx を適当に指定すると正しい$securekeyが表示されます。

# php /var/www/html/admin/cron_currency_rates.php secure_key=xxxxx
asd4567890jj

これをクローンジョブのsecure_keyに指定します。

#Prestashop currency update schedule
* 2 * * * docker exec -u www-data prestashop-container php /var/www/html/admin/cron_currency_rates.php secure_key=asd4567890jj

ロケーションデータの挿入

ロケーションデータGeoLite2 Cityを下記サイトからダウンロード
https://www.maxmind.com/en/accounts/353548/geoip/downloads

展開したファイル GeoLite2-City.mmdbapp/Resources/geoip へコピーして
“Geolocation by IP address” を有効にします。

Gmail SMTPサーバの設定

テストメール送信時のバグ。Chromeの自動入力によるアカウントのパスワードでSMTPサーバにアクセスしているため。Chromeの自動入力設定を削除するか、自動入力されないアカウントで設定することにより回避。

E-Mailテンプレートの編集

ModernよりもClassicテーマの方がレイアウトが整然としていて見やすいです。

メールで使用される各テンプレートは、テーマ毎 (Modern, Classic)mails/themes に纏められています。

mails/themes フォルダ内の各テーマの twig ファイルから、html または txt 形式のファイルが作成されます(この作成作業は、管理画面のデザイン ---> Email Theme ---> Generate emails から行うか、以下のprestashop:mail:generateでも可能です)。

prestashop:mail:generate

# bin/console prestashop:mail:generate --help               
Usage:
  prestashop:mail:generate [options] [--] <theme> <locale> [<coreOutputFolder>] [<modulesOutputFolder>]

Arguments:
  theme                        Theme to use for mail templates.
  locale                       Which locale to use for the templates.
  coreOutputFolder             Output folder to export core templates.
  modulesOutputFolder          Output folder to export modules templates (by default same as core).

Options:
  -o, --overwrite[=OVERWRITE]  Overwrite existing templates [default: false]
  -h, --help                   Display this help message
  -q, --quiet                  Do not output any message
  -V, --version                Display this application version
      --ansi                   Force ANSI output
      --no-ansi                Disable ANSI output
  -n, --no-interaction         Do not ask any interactive question
  -e, --env=ENV                The Environment name. [default: "dev"]
      --no-debug               Switches off debug mode.
  -v|vv|vvv, --verbose         Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

ロケールと上書きオプションを指定してジェネレートコマンドを実行

# bin/console prestashop:mail:generate -o true classic ja-JP
# bin/console prestashop:mail:generate -o true classic en-US

また、作成されたテーマごとのメール送信テストは、 Email themes から行うことが出来ます(選択したテーマでのみ送信テストが可能)。


作成されたテンプレートをさらに細かく編集したい場合には、以下翻訳メニューから行うことが出来ます。

International ---> Translations ---> Modify Translations から以下の項目を選択

Core emails から編集するテンプレートを選択

テンプレートの編集箇所が多い場合は、直接twigファイルを編集したほうが良いかもしれません。上記テンプレートの {recycled_packaging_label} やフッター prestashop へのリンクを削除する場合は、メールコアの order_conf で該当する表の行を削除するか、

次のClassicテーマのtwigテンプレート

mails/themes/classic/conponents/footer.html.twig
mails/themes/classic/core/order_conf.html.twig

から該当箇所を削除し、以下のメニュー画面に従って言語毎に再作成します(編集後、所有権の修正を忘れずに)。


Gmail SMTPサーバによる送信メール内のイメージについて


メール関連ファイル

コントローラ
src/PrestaShopBundle/Controller/Admin/Configure/AdvancedParameters/EmailController.php

管理画面メール設定ファイル
src/PrestaShopBundle/Resources/config/routing/admin/configure/advanced_parameters/email.yml

テンプレート設定ファイル
src/PrestaShopBundle/Resources/config/services/core/mail_template.yml

  prestashop.core.mail_template.theme_folder_catalog:
    class: 'PrestaShop\PrestaShop\Core\MailTemplate\FolderThemeCatalog'
    arguments:
      - '%mail_themes_dir%'
      - '@prestashop.core.mail_template.theme_folder_scanner'
      - '@prestashop.core.hook.dispatcher'

  prestashop.core.mail_template.variables_builder:
    class: 'PrestaShop\PrestaShop\Core\MailTemplate\Layout\LayoutVariablesBuilder'
    arguments:
      - '@prestashop.core.hook.dispatcher'
      - '@prestashop.core.language.language_default_fonts_catalog'
      - mailThemesUrl: "@=service('prestashop.adapter.legacy.context').getMailThemesUrl()"

上記 mailThemesUrl は、
src/Adapter/LegacyContext.php

/**
     * Url to the mail themes folder
     *
     * @return string
     */
    public function getMailThemesUrl()
    {
        return $this->tools->getShopDomainSsl(true) . __PS_BASE_URI__ . $this->mailThemesUri;
    }

管理画面メール設定テンプレートフォルダ
src/PrestaShopBundle/Resources/views/Admin/Configure/AdvancedParameters/Email

Twig Configration
app/config/config.yml

# Twig Configuration
twig:
    autoescape:       "name"
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"
    form_themes:
        - 'PrestaShopBundle:Admin/TwigTemplateForm:bootstrap_4_horizontal_layout.html.twig'
    paths:
        '%admin_page%/Product': Product
        '%admin_page%/TwigTemplateForm': Twig
        '%admin_page%/Common': Common
        '%admin_page%/Configure/AdvancedParameters': AdvancedParameters
        '%admin_page%/Configure/ShopParameters': ShopParameters
        '%kernel.root_dir%/../modules': Modules
        '%mail_themes_dir%': MailThemes
    globals:
        webpack_server: false
        multistore_field_prefix: !php/const:PrestaShopBundle\Service\Form\MultistoreCheckboxEnabler::MULTISTORE_FIELD_PREFIX

送信メールテンプレート
mails/themes/modern/core/order_conf.html.twig

<img src="{{ mailThemesUrl }}/modern/assets/baseline-local_shipping-24px.png" style="margin-{{ align_right }}:10px">

ストアURL

ストアURLとSEO対策

Shop Parameters ---> Traffic & SEO ---> SEO & URLs

Customer Reassurance Module

セキュリティ、デリバリー、リターンポリシーの設定

Modules ---> Module Manager ---> Theme Module ---> Customer Assurance

登録ユーザ住所・配送先住所:国・都市選択メニュー

住所登録の際の国・都市のプルダウン選択メニューに表示させる項目の追加

左下 “Bulk actions” ボタンにより、一覧表から選択した 国(Countries)・都市(States)有効または無効にします。

International ---> Locations ---> "Countries" or "States"

Countries

States

:warning:
注)日本の都道府県がISOコード別に二重で登録されているため、片方を無効化。

日本語ローカライゼーション

Locarization ---> Languages ---> 日本語

ISOコードjp ではなく ja にしないと日本語の翻訳データがダウンロード出来ません。

日本語の翻訳データのダウンロード

Locarization ---> Languages ---> Import a localization pack ---> Japan
で日本語翻訳データのインポート(税、単位、都市、通貨、言語をチェック)。

日本語翻訳文中の変数は %s で前後に半角スペースを挿入すること。

File Structure

/app

This directory contains the configuration for the bundles and the framework.

It contains the following subdirectories:

  • /config: configuration files for database, parameters, services, etc.
  • /logs: execution logs
  • /Resources: different resources for the software, most notably the /translations subdirectory which contains translation resources for all the installed languages.
  • /test: reserved

This directory also includes the AppKernel.php file, which configures the Symfony application.

/controllers

Contains controllers – as in Model-View-Controller (or MVC), the software architecture used by PrestaShop. Each file controls a specific part of PrestaShop.

Controllers are separated in two directories:

  • /admin: contains legacy controllers for the Back Office
  • /front: contains controllers for the Front Office

/mails

Contains all HTML and text templates for e-mails sent by PrestaShop. Each language has its specific folder, where you can manually edit their content if you wish. PrestaShop contains a tool to edit your e-mails, located in the back office, in the Localization > Translation page.

Since 1.7.6 this directory also contains Mail themes.

/modules

Contains all of PrestaShop’s modules, each in its own folder.
If you wish to definitely remove a module, it is better to uninstall it from the back office.

/src

Contains the new architecture files (Core, Adapter and PrestaShop Bundle). To learn more, see Understanding the “src” folder.

  • Core: contains business logic classes
  • Adapter: business logic classes that still depend on legacy framework (for instance: Context, Dispatcher or constants);
  • PrestaShopBundle: classes that acts as a glue between PrestaShop classes and Symfony

Symfony controllers & routing

Read the Symfony documentation on Controllers and Routing.

src/PrestaShopBundle/Controller

Controller/
└── Admin
    ├── Configure
    │   ├── AdvancedParameters
    │   └── ShopParameters
    ├── Improve
    │   ├── Design
    │   ├── International
    │   ├── Modules
    │   ├── Payment
    │   └── Shipping
    └── Sell
        ├── Catalog
        ├── Customers
        ├── CustomerService
        ├── Orders
        └── Stats

Routing in PrestaShop

Routes are responsible for mapping a controller action to an url, you can read more about routing in symfony docs.

PrestaShop uses YAML files for service declaration and routing (NOT ANNOTATIONS).

Routes are declared in

src/PrestaShopBundle/Resources/config/admin

folder, following the menu organization.

The routing is organized as follows:

.
├── admin
│   ├── _common.yml
│   ├── configure
│   │   ├── advanced_parameters
│   │   ├── _configure.yml
│   │   └── shop_parameters
│   ├── improve
│   │   ├── design
│   │   ├── _improve.yml
│   │   ├── international
│   │   ├── modules
│   │   ├── payment
│   │   └── shipping
│   ├── _security.yml
│   └── sell
│       ├── catalog
│       ├── orders
│       ├── _sell.yml
│       └── stocks.yml
├── admin.yml
├── api
│   ├── attributes.yml
│   ├── categories.yml
│   ├── features.yml
│   ├── i18n.yml
│   ├── improve
│   │   └── design
│   ├── manufacturers.yml
│   ├── stock_movements.yml
│   ├── stocks.yml
│   ├── suppliers.yml
│   └── translations.yml
└── api.yml

URI, ディレクトリ

Name Language Example Type Front, back?
_PS_ROOT_DIR_ PHP /var/www/html/prestashop full path front + back
root_url Twig /prefix/
__PS_BASE_URI__ PHP /prefix/ relative url
baseAdminDir Javascript /prefix/admin-dev/ back
baseDir Javascript /prefix/ back
basename(PS_ADMIN_DIR) PHP admin-dev folder name back
prestashop.urls Javascript base_url:‘’, current_url:‘’, shop_domain_url:‘’, img_ps_url:‘’, img_cat_url:’’, … front
{$base_url} Smarty https://myshop.com/prefix/ full url back
{$base_url} Smarty
{$baseAdminUrl} Smarty /prefix/admin-dev/ relative url back
{$img_base_path} Smarty /admin-dev/ back
{$urls.base_url} Smarty https://myshop.com/prefix/ full url front

管理画面コントローラ


controllers/admin/AdminCountriesController.php

都市
controllers/admin/AdminStatesController.php

PHP syntax check

# php -l  <file>
        Syntax check only (lint)
# find . -type f -name '*.php' ! -path "./vendor/*" ! -path "./tests/*" -exec php -l -n {} \; | (! grep -v "No syntax errors detected")

Fixed

classes/State.php
County ---> Country, Counties ---> Countries

    /**
     * Has Countries.
     *
     * @param int $idState
     *
     * @return int
     */
    public static function hasCountries($idState)
    {
        return count(Country::getCountries((int) $idState));
    }

多言語対応

データベース上のルール

  • Tables which contain translations must end with the _lang suffix. For instance, ps_product_lang contains all the translations for the ps_product table.
  • Use the id_lang field to store the language associated with a record.

SQLテーブルデータ一覧

テーブルの追加・編集は以下sqlデータを参照のこと(自動インストール後はinstallディレクトリは削除されます)。

テーブルコンテンツ

テーブル Country

/* Country specific data */
CREATE TABLE `PREFIX_country` (
  `id_country` int(10) unsigned NOT NULL auto_increment,
  `id_zone` int(10) unsigned NOT NULL,
  `id_currency` int(10) unsigned NOT NULL DEFAULT '0',
  `iso_code` varchar(3) NOT NULL,
  `call_prefix` int(10) NOT NULL DEFAULT '0',
  `active` tinyint(1) unsigned NOT NULL DEFAULT '0',
  `contains_states` tinyint(1) NOT NULL DEFAULT '0',
  `need_identification_number` tinyint(1) NOT NULL DEFAULT '0',
  `need_zip_code` tinyint(1) NOT NULL DEFAULT '1',
  `zip_code_format` varchar(12) NOT NULL DEFAULT '',
  `display_tax_label` BOOLEAN NOT NULL,
  PRIMARY KEY (`id_country`),
  KEY `country_iso_code` (`iso_code`),
  KEY `country_` (`id_zone`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8mb4 COLLATION;

/* Localized country information */
CREATE TABLE `PREFIX_country_lang` (
  `id_country` int(10) unsigned NOT NULL,
  `id_lang` int(10) unsigned NOT NULL,
  `name` varchar(64) NOT NULL,
  PRIMARY KEY (`id_country`, `id_lang`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8mb4 COLLATION;

テーブル State

/* State localization info */
CREATE TABLE `PREFIX_state` (
  `id_state` int(10) unsigned NOT NULL auto_increment,
  `id_country` int(11) unsigned NOT NULL,
  `id_zone` int(11) unsigned NOT NULL,
  `name` varchar(64) NOT NULL,
  `iso_code` varchar(7) NOT NULL,
  `tax_behavior` smallint(1) NOT NULL DEFAULT '0',
  `active` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id_state`),
  KEY `id_country` (`id_country`),
  KEY `name` (`name`),
  KEY `id_zone` (`id_zone`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8mb4 COLLATION;

上記初期テーブル以外のテーブルはDoctrineにより作成されます。

関連ディレクトリ
src/PrestaShopBundle/Entity/